GcmListenerService和requestLocationUpdates

Flo*_*034 1 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);

}
Run Code Online (Sandbox Code Playgroud)

}

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

是onMessageReceived一个线程?

谢谢

mor*_*ork 5

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

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

new Handler(Looper.getMainLooper()).post(...)

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

但我不认为这会做你想要的.一旦您完成处理消息(即在onMessageReceived()上结束),GcmListenerService将自行停止(除非已经到达另一条消息),然后您将不再获得您的位置更新,因为我假设侦听器将在onDestroy()中取消注册.