如何让我的活动不停止工作

时间:2013-04-10 09:00:35

标签: android

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跟踪仍将跟踪我的位置,我在哪里犯了错误?

1 个答案:

答案 0 :(得分:1)

使用此代码,在onchangeLocation()方法中注册LocationManager。

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;
    }