服务未接收GPS回调

时间:2015-01-13 13:22:53

标签: android

我的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);
        }
    });
}

但它仍然不起作用......

关于我在这里缺少什么的想法?

1 个答案:

答案 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();

}