Android - GPS Listener

2019-08-05 09:43发布

I am developing an Android application which consists a few activities. I want to get updates from the GPS (onLocationChanged, onProviderDisabled, onProviderEnabled, onStatusChanged) no matter in which activity the user is currently using.

Where should I implement the LocationListener in order to get such a behaviour?

This is the class I have created:

public class MyLocationListener implements LocationListener{

private LocationManager locationManager;
private String provider;

    @Override
public void onLocationChanged(Location locationGPS) {

    //do something
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    Log.i("===========================", "==============================");
    Log.i("onProviderEnabled", "==============================");
    Log.i("===========================", "==============================");

}

@Override
public void onProviderDisabled(String provider) {

    Log.i("===========================", "==============================");
    Log.i("onProviderDisabled", "==============================");
    Log.i("===========================", "==============================");
}

标签: android gps
2条回答
【Aperson】
2楼-- · 2019-08-05 10:10

Create a Service and monitor location there or you can implement a LocationListener in a separate class and use it in every Activity, turning it on onResume() and shutting down onPause()

查看更多
神经病院院长
3楼-- · 2019-08-05 10:26

Start the location listener on the activity you wants to start the gps. To start the GPS you can use

LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new CTLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1.0f, locationListener);

and to stop the GPS you can use

locationManager.removeUpdates(locationListener);

Its better you write the GPS start on the onCreate()/onStart() and the GPS remove on the onDestroy() of a service and use that service. Otherwise once you stop the GPS the chance of starting the GPS again is less than 50% in some devices.

查看更多
登录 后发表回答