0
import android.app.Activity;

public class LocationTracking extends Activity {

    Button btnShowLocation;
    Button refresh;

    GPSTracker gps;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location_tracking);

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


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

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

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

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

                    // \n is for new line

                      ((TextView)findViewById(R.id.latitude)).setText(Double.toString(latitude));
                      ((TextView)findViewById(R.id.longitude)).setText(Double.toString(longitude));



                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }

            }
        });
        refresh.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                ((TextView)findViewById(R.id.latitude)).setText("");
                ((TextView)findViewById(R.id.longitude)).setText("");
            }
        });
        }
   }


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.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = 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
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    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 (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // 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;
    }

}

ネット上でこの gps トラッキング アクティビティを見つけました。すでに試してみましたが、完全に動作しますが、後で問題が発生しました。新しいアクティビティを開始すると、実行中に停止します。やりたいことは、開始しても停止しないことです誰かが電話をかけたり、メッセージを送ったりしている場合の新しいアクティビティの例 gps追跡は、どこで間違いを犯したかを追跡します。

4

1 に答える 1

1

このコードを使用して、LocationManager をonchangeLocation()メソッドに登録します。

public class NewLocationListener implements android.location.LocationListener {

    private final static String TAG = "LocationListener";
    private Context context = null;
    private LocationManager locationManager = null;

    private double latitude = 0.0;
    private double longitude = 0.0;
    /*public String newlatitude=null;
    public String newlongitude=null;*/
    private Location gpslocation=null;

    public void setDefault() {
        Log.v(TAG + ".setDefault", "GPS Co-ordinates initialised");

        latitude = 0.0;
        longitude = 0.0;

    }

    public NewLocationListener(Context ctx) {
        Log.v(TAG + ".LocationListener", "LocationListener constructor called");
        context = ctx;
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    }

    public void onProviderDisabled(String provider) {
        Log.v(TAG + ".onProviderDisabled", "onProviderDisabled method called");

    }

    public void onProviderEnabled(String provider) {
        Log.v(TAG + ".onProviderEnabled", "onProviderEnabled method called");

    }

    public void onLocationChanged(Location location) {

        gpslocation=location;
        Log.v(TAG + ".onLocationChanged", "onLocationChanged method called");
        //Toast.makeText(context, "onLocationChanged called", Toast.LENGTH_SHORT).show();


        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        if (gpslocation != null) {
            setLocationCoordinates(gpslocation);

        } else {
            Log.v(TAG + ".onLocationChanged", "couldn't get gps using onLocationChange");

            getLastKnownLocation();

        }

    }

    public void setLocationCoordinates(Location location) {
        try {

            double latNew = (location.getLatitude());
            double lonNew = (location.getLongitude());

            if (latNew != 0.0 && lonNew != 0.0) {

                Log.v(TAG + ".onLocationChanged", "New location co-ordinates are not 0");

            /*  setLatitude(latNew);
                setLongitude(lonNew);*/
                /*
                 * latitude = latNew; longitude = lonNew;
                 */

                String newlatitude=Double.toString(latNew);
                String newlongitude=Double.toString(lonNew);

                Log.v(TAG, "new latitude is" + newlatitude+" new longitude is" + newlongitude);
                //Toast.makeText(context, "lat: " + newlatitude+" lon: " + newlongitude, Toast.LENGTH_SHORT).show();


            } else {

                //Toast.makeText(context, "we got 0.0 value ", Toast.LENGTH_SHORT).show();
                Log.v(TAG + ".onLocationChanged", "we got 0.0 value ");
            }

        } catch (Exception e) {
            Log.v(TAG + ".onLocationChanged.Exception", "Exception is " + e);

        }
    }

    public void getLastKnownLocation() {
        Location location = locationManager.getLastKnownLocation(getBestProvider());

        gpslocation=location;
        if (gpslocation != null) {
            //Toast.makeText(context, "LastKnownLocation called", Toast.LENGTH_SHORT).show();
            setLocationCoordinates(gpslocation);

        } else {
            //Toast.makeText(context, "couldn't get LastKnownLocation", Toast.LENGTH_SHORT).show();
            Log.v(TAG + ".onLocationChanged","couldn't get gps using lastKnownLocation");
        }
    }

    public String getBestProvider() {
         locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
         Criteria criteria = new Criteria();
         criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
         criteria.setAccuracy(Criteria.NO_REQUIREMENT);
         String bestProvider = locationManager.getBestProvider(criteria, true);

        return bestProvider;
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.v(TAG + ".onStatusChanged", "onStatusChanged method called");

    }


    public double getLatitude() {

        if (gpslocation != null) {
            latitude = gpslocation.getLatitude();
        }   
        return latitude;
    }   
    public double getLongitude() {

        if (gpslocation != null) {
            longitude = gpslocation.getLongitude();
        }   
        return longitude;
    }
于 2013-04-10T09:21:57.057 に答える