android - GcmListenerService 和 requestLocationUpdates

标签 android locationmanager

使用新的 GcmListenerService,我正在尝试在收到消息时获取用户位置:

public class MobilAirGcmListenerService extends GcmListenerService {

private static final String TAG = "MobilAir:GcmIService";


@Override
public void onMessageReceived (String from, Bundle data) {

    final String message = data.getString("appehour");

    // Post notification of received message.

       lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, updateTime, distance, this );

    Log.i(TAG, "Received: " + message);

    Intent intentToBroadCast = new Intent(this, MobilAirNotificationClick.class);
    sendBroadcast(intentToBroadCast);

}

但是当 de locationManger 被调用时,我得到这个错误:无法在没有调用 Looper.prepare() 的线程中创建处理程序

onMessageReceived 是一个线程吗?

谢谢

最佳答案

onMessageReceived() 在线程池上被调用,以便: 1.不阻塞主线程,这样可以直接完成长时间运行的工作,而无需启动新的服务。 2. 确保一条需要很长时间处理的消息不会阻止处理其他(可能是实时的)消息。

但是池中的线程是原始 Java 线程,没有关联的循环器,您需要它来获取位置更新。您可以通过创建并发布到处理程序来开始在主循环器上请求位置更新:

新处理程序(Looper.getMainLooper()).post(...)

或者,如果您想获取所有消息的位置更新,您可以在 onCreate() 中注册您的监听器。

但我认为这不会如您所愿。一旦您处理完消息(即在 onMessageReceived() 上结束),GcmListenerService 将自行停止(除非另一条消息已经到达),然后您将不再获得位置更新,因为我假设监听器将在 onDestroy() 中注销。

关于android - GcmListenerService 和 requestLocationUpdates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30750631/

相关文章:

android - 从不同的 Activity android 访问 LocationManager 回调

android - 位置管理器没有正确检查

android - kotlin coroutine throws java.lang.IllegalStateException : Already resumed, 但得到值 Location

android - 确定 Subject 何时没有订阅者

android - 获取可用的 wifi 连接后,以编程方式连接特定的 wifi

android - 如何防止系统字体大小改变对android应用程序的影响?

ios - addressDictionary 随机返回 nil

android - 从 GCMIntentService 获取 Android 位置

android - 更改 ListView 上所选项目的背景颜色

android - 即使 setFocusable(true),PopupWindow 中的 EditText 也不显示键盘