2

当他收到 GCM 通知时,我想在 Android 中获取用户的位置。
所以在我的GCMIntentService extends GCMBaseIntentService我这样做:

   @Override
    protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Received message. Extras: " + intent.getExtras());
        String message = getString(R.string.gcm_message);
        displayMessage(context, message);
        syncLocations(context);

    }

在syncLocation中,我正在正确地获取位置

public void syncLocations(Context context)
    {

        locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);

            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 0, 0,
                    mLocationListener);
            locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 1000, 0,
                    mLocationListener);

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

        @Override
        public void onProviderEnabled(
                String provider)
        {}

        @Override
        public void onProviderDisabled(
                String provider)
        {}

        @Override
        public void onLocationChanged(
                Location location)
        {
//HANDLE LOCATION
        }
    };

如果从应用程序内部调用syncLocation,则它可以正常工作。

但是当我从通知 onMessage() 调用它时,它会进入方法,但永远不会调用 onLocationChanged。我怀疑这与上下文有关。

谁能给我任何信息为什么它不起作用?
谢谢

4

1 回答 1

3

谁能给我任何信息为什么它不起作用?

Because GCMIntentService is an IntentService and goes away (via stopSelf()) shortly after onMessage() returns. You cannot reliably do things like register listeners for location changes from an IntentService.

Also, bear in mind that the device may be asleep when the GCM message comes in. GCMIntentService will keep the device awake long enough to call onMessage(), but once onMessage() returns, the device can fall back asleep.

于 2013-03-30T15:27:52.607 回答