4

我编写了一个实现 LocationListener 接口的 IntentService。当第一次调用 OnLocationChanged() 方法时,服务应该发送一条消息。但是永远不会调用 OnLocationChanged()。这是我的代码:

public class MyIntentService extends IntentService implements LocationListener {

    private int result = Activity.RESULT_CANCELED;
    protected Messenger mMessenger;
    protected LocationManager mLocationManager = null;

    public MyIntentService() {
        super("LocationService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i(TAG, "Got starting intent: " + intent.toString());
        Bundle extras = intent.getExtras();

        if (extras != null) {
            Messenger = (Messenger) extras.get("MESSENGER");

            if(mLocationManager == null) {  
            mLocationManager =  (LocationManager) MyIntentService.this
                                    .getSystemService(Context.LOCATION_SERVICE);
            }
            String provider = LocationManager.GPS_PROVIDER;
            boolean gpsIsEnabled = mLocationManager.isProviderEnabled(provider);

            if(gpsIsEnabled) {
                Context con = MyIntentService.this;
                mLocationManager.requestLocationUpdates(provider, 0, 0,
                                                        MyIntentService.this);
            } 
            else {
                Log.i(TAG, "NO GPS!");
            }
        }

    @Override
    public void onLocationChanged(Location location) {
        Log.i(TAG, "Got Location");
        Log.i(TAG, "Got Messenger: " + mMessenger.toString() 
                    + "\nand Location Manager: " + mLocationManager.toString());

        if(mMessenger != null && mLocationManager != null){
            result = Activity.RESULT_OK;
            Message msg = Message.obtain();
            msg.arg1 = result;
            msg.obj = location;
            mLocationManager.removeUpdates(MyIntentService.this);

            try { mMessenger.send(msg); } 
            catch (RemoteException e) {
                Log.i(TAG, "Exception caught : " + e.getMessage());
            }
        }
    }

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {}

}

有人有想法吗?

4

1 回答 1

7

我编写了一个实现 LocationListener 接口的 IntentService。

这不是一个好主意。AnIntentService不应该做任何超出该onHandleIntent()方法的事情。

当第一次调用 OnLocationChanged() 方法时,服务应该发送一条消息。但是永远不会调用 OnLocationChanged()。

这并不奇怪,因为服务将在创建后一毫秒左右被销毁,具体取决于您的实现。

如果您的目标是始终拥有一个合理的当前位置,请尝试Little Fluffy Location Library。或者,考虑我的LocationPoller.

于 2012-04-25T17:59:19.013 回答