我有一项服务来更新我的应用中的位置。当我启动我的应用程序禁用GPS时,返回到Android菜单并启用GPS,最后回到我的应用程序(该服务尚未被销毁),onProviderEnabled永远不会被调用。有人可以帮忙吗?
更新:如果我重新启动应用程序,则启用提供程序。仅调用onProviderEnabled ...
在我需要定位的每项活动中
super.onCreate(savedInstanceState);
//....
// Bind location service
bindService(new Intent(this, LocationService.class), mConnection, Context.BIND_AUTO_CREATE);
//....
和
@Override
protected void onDestroy() {
super.onDestroy();
// Unbind LocationService
ItemDetail.this.unbindService(mConnection);
}
,服务是
public class LocationService extends Service implements LocationListener {
LocationManager locationManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
// Update after minimum 5 minutes and if user has moved at least 100 meters.
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5 * 60 * 1000, 100, this);
Location loc = getBestLocation(locationManager);
if(loc!=null){
GlobalVars.lat = (Double) (loc.getLatitude());
GlobalVars.lng = (Double) (loc.getLongitude());
}
}
}
public void onLocationChanged(Location loc) {
GlobalVars.lat = (Double) (loc.getLatitude());
GlobalVars.lng = (Double) (loc.getLongitude());
}
public static Location getBestLocation(LocationManager locationManager) {
Location location_gps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location location_network = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// If both are available, get the most recent
if(location_gps!=null && location_network !=null) {
return (location_gps.getTime() > location_network.getTime())?location_gps:location_network;
}
else if(location_gps==null && location_network ==null){
return null;
}
else
return (location_gps==null)?location_network:location_gps;
}
public void onProviderEnabled(String s){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5 * 60 * 1000, 100, this);
}
public void onProviderDisabled(String s){
locationManager.removeUpdates(this);
GlobalVars.lat = null;
GlobalVars.lng = null;
}
public void onStatusChanged(String s, int i, Bundle b){}
@Override
public void onDestroy() {
locationManager.removeUpdates(this);
}
}
答案 0 :(得分:2)
在LocationService.onCreate()
方法中,您的代码会检查GPS提供商是否已停用。
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){...}
但是只有在已经启用的情况下才启动订阅。请注意,您的侦听器从未在LocationManager
中注册,并且不会接收任何已禁用或启用的位置提供程序的更新。而是将onCreate()
方法更改为始终调用
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5 * 60 * 1000, 100, this);