2

Android開発は初めてです。

Web サービスを使用してロケーション アドレスを取得しようとしましたが、このコードを起動したときにクラスが見つからないという例外が発生しました。

サービス クラスのコード....

public class MWService extends Service implements LocationListener {


private LocationManager myLocationManager;
private LocationProvider myLocationProvider;
private NotificationManager myNotificationManager;
private long frequency;
private double total_distance = 0;
private Location currentLocation;
public static final String BROADCAST_ACTION = "com.motorvehicle.android";
private final Handler handler = new Handler();
Intent intent;
private GeocoderHelper geocoder  = new GeocoderHelper();
private boolean isStart=true;
private Location startLocation,endLocation;
private String startAddress="";
private String endAddress="";
private JSONArray jarray = new JSONArray();
private boolean isInternet;
//private final Handler handler = new Handler();

public void onLocationChanged(Location newLocation) {
    try {
        System.out.println("latitude current :"+currentLocation.getLatitude());
        System.out.println("latitude current :"+currentLocation.getLongitude());
        System.out.println("latitude new  :"+newLocation.getLatitude());
        System.out.println("latitude new  :"+newLocation.getLongitude());
        System.out.println("distance total :"+total_distance);
        //System.out.println(distance(22.306813, 73.180239,22.301016, 73.177986, 'K') + " Kilometers\n");
        double diff = 0.0;
        diff = currentLocation.getLatitude()- newLocation.getLatitude();
        System.out.println("difference ::"+diff);
        if(diff != 0){
            total_distance = total_distance + currentLocation.distanceTo(newLocation);
        }


        if(isStart){
            isStart = false;
            startLocation = newLocation;
        /*  if(InternetAvailable()){
                //startAddress =    geocoder.fetchCityName(getApplicationContext(),newLocation);
                System.out.println("start address:"+startAddress);
            }*/

        }else{
            endLocation = newLocation;
            /*if(InternetAvailable()){
                //endAddress =  geocoder.fetchCityName(getApplicationContext(),newLocation);
                System.out.println("endAddress :"+endAddress);
            }*/
        }

        currentLocation = newLocation;
    } catch (Exception e) {
        currentLocation = newLocation;
        e.printStackTrace();
    }
}

public boolean InternetAvailable() {

    Thread t = new Thread(new Runnable() {


        @Override
        public void run() {
            // while(isStopMe){
            System.out.println("This is inside ................. :");
            try {
                if (!checkConnection()) {
                    System.out.println("No Internet Connectivity");
                    isInternet = false;
                    System.out.println("First");
                } else {
                    if (inetAddr()) {
                        System.out.println("Net Connectivity is Present");
                        isInternet = true;
                        System.out.println("Second");
                    } else {
                        if (mobileConnect()) {
                            System.out.println("THIRD");
                            if (inetAddr()) {
                                System.out
                                        .println("Net Connectivity is Present");
                                isInternet = true;
                                System.out.println("FOURTH");
                            } else {
                                System.out
                                        .println("No Internet Connectivity");
                            isInternet = false;
                                System.out.println("FIFTH");
                            }
                        } else {
                            System.out.println("No Internet Connectivity");
                            isInternet = false;
                            System.out.println("SIX");
                        }
                    }
                }
            } catch (Exception ex) {
                System.out.println("Leak ko catch");
            }

        }
    });
    t.start();
    try {
        t.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return isInternet;
}


public boolean checkConnection() {
    boolean connected = false;
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm != null) {
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if ((ni.getTypeName().equalsIgnoreCase("WIFI") || ni
                    .getTypeName().equalsIgnoreCase("MOBILE"))
                    & ni.isConnected() & ni.isAvailable()) {
                connected = true;
            }
        }
    }
    return connected;
}

public boolean inetAddr() {
    boolean x1 = false;

    try {
        Socket s = new Socket();
        s.connect(new InetSocketAddress("ntp-nist.ldsbc.edu",37),3000);
        InputStream is = s.getInputStream();

        Scanner scan = new Scanner(is);

        while(scan.hasNextLine()){

            System.out.println(scan.nextLine());
            x1 = true;
        }
    } catch (IOException e) {

        x1 = false;

    }
    return x1;
}
public boolean mobileConnect() {
    boolean conn = false;
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNet = cm
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (activeNet != null) {
        conn = true;
    } else {
        conn = false;
    }
    return conn;
}

@SuppressWarnings("deprecation")
private void myNotify(String text) {
    Notification notif = new Notification(R.drawable.ic_launcher, text, System
            .currentTimeMillis());
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, MainActivity.class), 0);
    notif.setLatestEventInfo(this, "MotorVehicleApp", text, contentIntent);
    // notif.defaults = Notification.DEFAULT_VIBRATE;
    myNotificationManager.notify((int) System.currentTimeMillis(), notif);
}

@Override
public void onCreate() {
    super.onCreate();


     String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if(!provider.contains("gps")){ //if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3")); 
            sendBroadcast(poke);
        }


    intent = new Intent(BROADCAST_ACTION);
    android.util.Log.d("MWD", "creating");
    myLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    System.out.println("location manager:"+myLocationManager.getAllProviders());
    myLocationProvider = myLocationManager.getProvider("gps");
    myNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    updatePreferences();



    handler.post(new Runnable() {
        @Override public void run() { 
            Toast.makeText(getApplicationContext(), "Address:"+startAddress, Toast.LENGTH_LONG).show(); } });
}
public void updatePreferences() {
    // sync local variables with preferences
    android.util.Log.d("NWD", "updating preferences");
    frequency = 10;
    // update the LM with the new frequency
    myLocationManager.removeUpdates(this);
    myLocationManager.requestLocationUpdates(myLocationProvider.getName(),frequency, 0, this);
}
@Override
public void onDestroy() {
    super.onDestroy();
    /////------set edittext editable        

     android.util.Log.d("NWD", "destroying");

     System.out.println("Inside on destroy of MWService");
     myLocationManager.removeUpdates(this);
    //myNotify("stopping");

    InsertTripDetails_AsyncTask insert = new InsertTripDetails_AsyncTask();
    insert.execute();

    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(provider.contains("gps")){ //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
    handler.removeCallbacks(sendUpdatesToUI);
}

@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    android.util.Log.d("NWD", "starting");
    currentLocation = myLocationManager.getLastKnownLocation(myLocationProvider.getName());
    //myNotify("starting"); 

    handler.postDelayed(sendUpdatesToUI, 3000); // 1 sec

}
private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            System.out.println("total_distance::"+total_distance);
            intent.putExtra("distance",(total_distance/1000));
            sendBroadcast(intent);
            handler.postDelayed(this, 3000);
        }
 };

public void onProviderDisabled(String arg0) {

}

public void onProviderEnabled(String arg0) {

}

public void onStatusChanged(String arg0, int arg1, Bundle arg2) {

}

@Override
public IBinder onBind(Intent arg0) {
    return null; // this is for heavy IPC, not used
}
private class InsertTripDetails_AsyncTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        try {


                try {
                    //InternetAvailable()
                    if(InternetAvailable()){
                        startAddress =  geocoder.fetchCityName(getApplicationContext(),startLocation);
                        System.out.println("start address:"+startAddress);
                        endAddress = geocoder.fetchCityName(getApplicationContext(),endLocation);
                        System.out.println("end address:"+endAddress);
                    }else{
                        System.out.println("internet not available");
                    }

                    // Internet not available when data are store in latitude and longitute format
                    if(startAddress.equalsIgnoreCase("") && endAddress.equalsIgnoreCase("")){
                        DecimalFormat sd = new DecimalFormat("##.##");
                        System.out.println("1 lat:"+sd.format(startLocation.getLatitude()) +" long:"+sd.format(startLocation.getLongitude())+",lat:"+sd.format(endLocation.getLatitude()) +" long:"+sd.format(endLocation.getLongitude()));

                    }else if(startAddress.equalsIgnoreCase("")){
                        DecimalFormat sd = new DecimalFormat("##.##");
                        System.out.println("2 lat:"+sd.format(startLocation.getLatitude()) +" long:"+sd.format(startLocation.getLongitude())+","+endAddress);

                    }else if(endAddress.equalsIgnoreCase("")){
                        DecimalFormat sd = new DecimalFormat("##.##");
                        try {
                            System.out.println(startAddress+",3 lat:"+sd.format(endLocation.getLatitude()) +" long:"+sd.format(endLocation.getLongitude()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    else{
                        System.out.println(startAddress+" "+ endAddress);
                    }



                } catch (Exception e) {
                e.printStackTrace();
              }



                } catch (Exception e) {

                    e.printStackTrace();
                    System.out.println("In catch of webservice thus no internet");

                }


        return "dfs";
            }
            @Override
            protected void onPostExecute(String result) {

            }
}

}

ジオコーダー クラスのコード

public class GeocoderHelper
{
private static final AndroidHttpClient ANDROID_HTTP_CLIENT = AndroidHttpClient.newInstance(GeocoderHelper.class.getName());

private String address="";
private Location i_Location;
private Context i_Context;
public String fetchCityName(final Context contex, final Location location)
{
    i_Location = location;
    i_Context = contex;
  try {
        return new Address().execute().get();
    } catch (Exception e) {

        return address;

    } 
}



public class Address extends AsyncTask<Void, Void, String>
{



    @SuppressWarnings("unused")
    @Override
    protected String doInBackground(Void... params)
    {
        String cityName = null;

        if (Geocoder.isPresent())
        {
            try
            {
                System.out.println("location latitude is"+i_Location.getLatitude());
                System.out.println("location longitude is"+i_Location.getLongitude());

                Geocoder geocoder = new Geocoder(i_Context, Locale.getDefault());
                List<android.location.Address> addresses = geocoder.getFromLocation(i_Location.getLatitude(), i_Location.getLongitude(), 1);
                if (addresses.size() > 0)
                {
                    //cityName = addresses.get(0).getLocality();
                    address = addresses.get(0).getLocality();
                    System.out.println("geocoder inside present address is"+address);

                }
            }
            catch (Exception ignored)
            {
                // after a while, Geocoder start to trhow "Service not availalbe" exception. really weird since it was working before (same device, same Android version etc..
            }
        }

        if (cityName != null) // i.e., Geocoder succeed
        {
            return cityName;
        }
        else // i.e., Geocoder failed
        {
            return fetchCityNameUsingGoogleMap();
        }

    }

    // Geocoder failed :-(
    // Our B Plan : Google Map
    private String fetchCityNameUsingGoogleMap()
    {


        try
        {
            String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + i_Location.getLatitude() + ","
                    + i_Location.getLongitude() + "&sensor=false&language=fr";

            JSONObject googleMapResponse = new JSONObject(ANDROID_HTTP_CLIENT.execute(new HttpGet(googleMapUrl),
                    new BasicResponseHandler()));

            // many nested loops.. not great -> use expression instead
            // loop among all results
            JSONArray results = (JSONArray) googleMapResponse.get("results");
            for (int i = 0; i < results.length(); i++)
            {
                // loop among all addresses within this result
                JSONObject result = results.getJSONObject(i);
                address = result.getString("formatted_address");
                System.out.println("map address:"+address);
                break;

      /*          if (result.has("address_components"))
                {
                    JSONArray addressComponents = result.getJSONArray("address_components");
                    // loop among all address component to find a 'locality' or 'sublocality'
                    for (int j = 0; j < addressComponents.length(); j++)
                    {
                        JSONObject addressComponent = addressComponents.getJSONObject(j);
                        if (result.has("types"))
                        {
                            JSONArray types = addressComponent.getJSONArray("types");

                            // search for locality and sublocality
                            String cityName = null;
                            String ROUTE= null;

                            for (int k = 0; k < types.length(); k++)
                            {

                                if ("locality".equals(types.getString(k)) && cityName == null)
                                {
                                    if (addressComponent.has("long_name"))
                                    {
                                        cityName = addressComponent.getString("long_name");
                                    }
                                    else if (addressComponent.has("short_name"))
                                    {
                                        cityName = addressComponent.getString("short_name");
                                    }
                                }
                                if ("sublocality".equals(types.getString(k)))
                                {
                                    if (addressComponent.has("long_name"))
                                    {
                                        cityName = addressComponent.getString("long_name");
                                    }
                                    else if (addressComponent.has("short_name"))
                                    {
                                        cityName = addressComponent.getString("short_name");
                                    }
                                }
                            }
                            if (cityName != null)
                            {
                                address = cityName;
                                return cityName;

                            }
                        }
                    }
                }*/
            }
        }
        catch (Exception ignored)
        {
            ignored.printStackTrace();
        }
        return address;
    }

    protected void onPostExecute(String result)
    {

          super.onPostExecute(result);
    }
}
}

MAinActivity クラスのコード

public class MainActivity extends Activity {
//private final Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    startService(new Intent(MainActivity.this,MWService.class));



}

@Override
protected void onPause() {
        super.onPause();
        stopService(new Intent(MainActivity.this,MWService.class));
}

}

インターネットと AccessFineLocation の両方について、menifest ファイルで使用許可を持っています。

私のlogcatメッセージ.....

10-31 13:40:41.937: ERROR/AndroidRuntime(825): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.address2/com.example.android.MainActivity}: java.lang.ClassNotFoundException: com.example.android.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.address2-1.apk]
10-31 13:40:41.937: ERROR/AndroidRuntime(825): Caused by: java.lang.ClassNotFoundException: com.example.android.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.address2-1.apk]

私のメニフェストファイルのコード....

<uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="17" />
 <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.android.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name="MWService"></service>
</application>
4

1 に答える 1

0

私のコードを使用してください。座標を使用して現在の住所を見つけることができましたが、そのためには Wi-Fi と GPS を有効にする必要があります。最初に、これらすべての権限を Android マニフェスト ファイルに追加します

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

AndroidGPSTrackingActivity.java*

package com.example.gpstracking;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;

public class AndroidGPSTrackingActivity extends Activity {

    Button btnShowLocation;

    // GPSTracker class
    GPSTracker gps;
    ToggleButton gpstoggle,wifitoggle,datatoggle;
    static WifiManager wifiManager;
    LocationManager lm;
    WebView web;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        gpstoggle = (ToggleButton) findViewById(R.id.gps);
        wifitoggle = (ToggleButton) findViewById(R.id.wifi);

        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 

        lm = (LocationManager) getSystemService(LOCATION_SERVICE);

        //gps toggle
        gpstoggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    final Intent poke = new Intent();
                    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
                    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                    poke.setData(Uri.parse("3")); 
                    getApplicationContext().sendBroadcast(poke);
                }
                else{
                    final Intent poke = new Intent();
                    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
                    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                    poke.setData(Uri.parse("3")); 
                    getApplicationContext().sendBroadcast(poke);
                }
            }
        });
        //wifi toggle
        wifitoggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    wifiManager.setWifiEnabled(true);
                }
                else{
                    wifiManager.setWifiEnabled(false);
                }
            }
        });

        //data toggle
        datatoggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    ConnectivityManager dataManager;
                    dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                    Method dataMtd = null;

                    try {
                        dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
                        dataMtd.setAccessible(true);
                        dataMtd.invoke(dataManager, true);

                    } catch (NoSuchMethodException e1) {
                        e1.printStackTrace();
                    }
                    catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }  
                    catch (SecurityException e) {
                        e.printStackTrace();
                    } 

                }
                else{
                    ConnectivityManager dataManager;
                    dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                    Method dataMtd = null;

                    try {
                        dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
                        dataMtd.setAccessible(false);
                        dataMtd.invoke(dataManager, false);


                    } catch (NoSuchMethodException e1) {
                        e1.printStackTrace();
                    }
                    catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }  
                    catch (SecurityException e) {
                        e.printStackTrace();
                    } 

                }
            }
        });

        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {        
                // create class object
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                // check if GPS enabled     
                if(gps.canGetLocation()){

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
                    List<Address> addresses = null;
                    try {
                        addresses = gcd.getFromLocation(latitude, longitude, 1);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if(!(addresses == null)){
                        if (!addresses.isEmpty() ){
                            System.out.println(addresses.get(0).getLocality());

                            Address address = addresses.get(0);

                            String addressText = String.format("%s, %s, %s, %s, %s, %s",
                                    address.getAddressLine(0),
                                    address.getAddressLine(1),
                                    address.getAddressLine(2),
                                    address.getAddressLine(3),
                                    address.getPhone(),
                                    address.getPremises());

                            System.out.println(addressText);

                            // \n is for new line
                            Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                        }else{
                            // can't get location
                            // GPS or Network is not enabled
                            // Ask user to enable GPS/network in settings
                            gps.showSettingsAlert();
                        }
                    }else{
                        // can't get location
                        // GPS or Network is not enabled
                        // Ask user to enable GPS/network in settings
                        gps.showSettingsAlert();
                    }

                }

            }
        });
    }

}

GPSTracker.java

package com.example.gpstracking;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            boolean wifiEnabled = AndroidGPSTrackingActivity.wifiManager.isWifiEnabled();

            ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

            this.canGetLocation = true;

            // if DATA Enabled get lat/long using WIFI Services
            if (activeNetwork.isConnected()) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                }
            }
            // if WIFI Enabled get lat/long using WIFI Services
            if (wifiEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);

                    }
                }
            }
            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }       
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button android:id="@+id/btnShowLocation" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Location"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

    <ToggleButton
        android:id="@+id/gps"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnShowLocation"
        android:layout_alignRight="@+id/btnShowLocation"
        android:layout_marginBottom="49dp"
        android:layout_marginRight="72dp"
        android:text="GPS"
         />

    <ToggleButton
        android:id="@+id/wifi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/gps"
        android:layout_alignBottom="@+id/gps"
        android:layout_alignLeft="@+id/btnShowLocation"
        android:layout_marginLeft="79dp"
        android:text="WIFI" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/gps"
        android:layout_alignLeft="@+id/btnShowLocation"
        android:text="GPS"
        android:textSize="15sp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignBottom="@+id/textView1"
        android:layout_marginLeft="61dp"
        android:layout_toRightOf="@+id/textView1"
        android:text="WIFI"
        android:textSize="15sp" />

</RelativeLayout>
于 2013-10-31T08:34:59.650 に答える