requestLocationUpdates()在单独的Thread中

idk*_*ing 6 android location android-location

我需要requestLocationUpdates()在一个单独的线程中,以便不阻止我的应用程序的其余部分(它将在大多数时间运行).最好的方法是什么?

Dav*_*ser 18

当您调用requestLocationUpdates()此选项时,只表示您希望在用户位置更改时回叫.此调用不需要花费大量时间,可以在主线程上进行.

当用户的位置发生变化时(根据您传递给的标准requestLocationUpdates()),您的监听器将通过onLocationChanged()或通过Intent(通过您传递给哪些参数requestLocationUpdates())回叫.如果你在onLocationChanged()那时做了很多处理,你不应该在主线程上运行这个方法,但是你应该只启动一个后台线程(或者发布Runnable一个后台线程并在后台线程上完成你的工作.

另一种选择是启动a HandlerThread并提供Looperfrom HandlerThread作为参数requestLocationUpdates().在这种情况下,回调onLocationChanged()将在HandlerThread.这看起来像这样:

    HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
    handlerThread.start();
    // Now get the Looper from the HandlerThread
    // NOTE: This call will block until the HandlerThread gets control and initializes its Looper
    Looper looper = handlerThread.getLooper();
    // Request location updates to be called back on the HandlerThread
    locationManager.requestLocationUpdates(provider, minTime, minDistance, listener, looper);
Run Code Online (Sandbox Code Playgroud)

  • 我失去了一个星期试图寻找解决方案,你先生救了我.我不能够感谢你. (2认同)