Android - GPS Listener

痴心易碎 提交于 2019-12-24 10:45:48

问题


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("===========================", "==============================");
}

回答1:


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.




回答2:


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()



来源:https://stackoverflow.com/questions/6138198/android-gps-listener

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!