简体   繁体   English

GcmListenerService和requestLocationUpdates

[英]GcmListenerService and requestLocationUpdates

With the new GcmListenerService i'm trying to get the user location when a message is received : 使用新的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);

}

} }

but when de locationManger is called i get this error : Can't create handler inside thread that has not called Looper.prepare() 但是当调用de locationManger时出现此错误:无法在未调用Looper.prepare()的线程内创建处理程序

is onMessageReceived a thread ? 是onMessageReceived线程?

Thank you 谢谢

onMessageReceived() is invoked on a thread pool in order to: 1. Not block the main thread, so that long running work can be done directly without having to start a new service. 在线程池上调用onMessageReceived()的目的是:1.不阻塞主线程,这样就可以直接执行长时间运行的工作,而不必启动新服务。 2. Make it so one message that takes a long time to process won't block other (potentially real time) messages from being handled. 2.确保处理一条需要很长时间的消息不会阻止其他(可能是实时的)消息被处理。

However the threads in the pool are raw Java threads, and don't have an associated looper, which you need to get location updates. 但是,池中的线程是原始Java线程,并且没有关联的循环程序,您需要获取该循环程序来更新位置。 You can start requesting location updates on the main looper via creating and posting to a handler: 您可以通过创建并发布到处理程序来开始在主循环器上请求位置更新:

new Handler(Looper.getMainLooper()).post(...) 新的Handler(Looper.getMainLooper())。post(...)

Or if you want to get location updates for all messages, you could register your listener in onCreate(). 或者,如果您想获取所有消息的位置更新,则可以在onCreate()中注册您的侦听器。

But I don't think this is going to do what you want. 但是我不认为这会做您想要的。 As soon as you have finished processing the message (ie get to the end on onMessageReceived()), the GcmListenerService will stop itself (unless another message already arrived), and then you won't get your location updates any more as I assume the listener will be unregistered in onDestroy(). 一旦您完成了对消息的处理(即onMessageReceived()的末尾),GcmListenerService就会自行停止(除非另一条消息已经到达),然后您将不再获得位置更新,因为我假设监听器将在onDestroy()中注销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM