android - 从 GCMIntentService 获取 Android 位置

标签 android locationmanager google-cloud-messaging

我想在 Android 中获取用户收到 GCM 通知时的位置。
所以在我的 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 从未被调用。我怀疑这与上下文有关。

任何人都可以给我任何信息为什么它不起作用吗?
谢谢

最佳答案

Can anyone please give me any info why it isn't working ?

因为 GCMIntentService 是一个 IntentService,并且在 onMessage() 后不久就消失(通过 stopSelf())返回。您无法可靠地执行诸如从 IntentService 注册位置更改监听器之类的操作。

此外,请记住,当 GCM 消息传入时,设备可能会处于 sleep 状态。GCMItentService 将使设备保持清醒状态足够长的时间来调用 onMessage(),但是一旦onMessage()返回,设备就可以重新进入休眠状态。

关于android - 从 GCMIntentService 获取 Android 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15719606/

相关文章:

android - MapBox queryRenderedFeatures 返回太多值

android - getLastKnownLocation 仅在位置变化 ~50 m 时更新。为什么?

Azure NotificationHub 发送推送时凭据无效

android - 用于聊天应用程序的 GCM 和 App Engine

android - 编译play-services-gcm :8. 4.0 时出现版本冲突错误

android - 在协调器布局中带有 anchor 的 FAB 在 android pre-lollipop 中有额外的边距

Android快捷方式位图启动器图标大小

android - 在 Android 中打开 Facebook Messenger

android - 当所有位置提供程序都被禁用时,如何在 android 中获取位置?

java - `locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);` 始终返回 true