我的app上有一个后台Service
作为LocationListener运行。
我们的想法是让这项服务成为位置更新的唯一入口点,然后通过广播或事件总线在应用程序中传播这些服务。
问题是,我在使用LocationManager.NETWORK_PROVIDER
时只收到回调,而在使用LocationManager.GPS_PROVIDER
时则没有回复。
我在this SO ticket中看到我需要在主线程上运行代码才能使回调正常工作。
这就是我实现以下代码的原因:
@Override
public void onCreate() {
super.onCreate();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new MyLocationListener();
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
mProvider = LocationManager.GPS_PROVIDER;
} else {
mProvider = LocationManager.NETWORK_PROVIDER;
}
handler = new Handler(getApplicationContext().getMainLooper());
startOrRestartLocationTracking();
}
private void startOrRestartLocationTracking() {
handler.post(new Runnable() {
@Override
public void run() {
mLocationManager.removeUpdates(mLocationListener);
mLocationManager.requestLocationUpdates(mProvider, TIME_INTERVAL, DISTANCE_INTERVAL, mLocationListener);
}
});
}
但它仍然不起作用......
关于我在这里缺少什么的想法?
答案 0 :(得分:0)
申请类:
public class MyApplication extends Application {
public static Context m_appContext = null;
public void onCreate() {
MyApplication.m_appContext = getApplicationContext();
}
}
服务:
@Override
public void onCreate() {
super.onCreate();
mLocationManager = (LocationManager) MyApplication.m_appContext.getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new MyLocationListener();
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
mProvider = LocationManager.GPS_PROVIDER;
} else {
mProvider = LocationManager.NETWORK_PROVIDER;
}
handler = new Handler(getApplicationContext().getMainLooper());
startOrRestartLocationTracking();
}