我需要将 requestLocationUpdates()
放在一个单独的线程中,以免它阻塞我应用程序的其余部分(它将在大部分时间运行)。最好的方法是什么?
最佳答案
当您调用 requestLocationUpdates()
时,这仅表示您希望在用户位置更改时被回调。此调用不会花费大量时间,并且可以在主线程上进行。
当用户的位置发生变化时(并根据您传递给 requestLocationUpdates()
的条件),您的监听器将通过 onLocationChanged()
回调或通过 通知>Intent
(取决于您传递给 requestLocationUpdates()
的参数)。如果你在 onLocationChanged()
中做了很多处理,那么你不应该在主线程上运行这个方法,而你应该只启动一个后台线程(或者发布一个 Runnable
到后台线程并在后台线程上执行您的工作。
另一种选择是启动一个 HandlerThread
并将 HandlerThread
中的 Looper
作为参数提供给 requestLocationUpdates()
。在这种情况下,将在 HandlerThread
上对 onLocationChanged()
进行回调。这看起来像这样:
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);
关于android - requestLocationUpdates() 在单独的线程中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29219144/