使用新的 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/