【问题标题】:requestLocationUpdates() in separate ThreadrequestLocationUpdates() 在单独的线程中
【发布时间】:2015-05-26 23:14:02
【问题描述】:

我需要requestLocationUpdates() 位于一个单独的线程中,以免它阻塞我的应用程序的其余部分(它将在大部分时间运行)。最好的方法是什么?

【问题讨论】:

    标签: android location android-location


    【解决方案1】:

    当您调用requestLocationUpdates() 时,这只是表示您希望在用户位置更改时被回叫。此调用不会花费大量时间,并且可以在主线程上进行。

    当用户的位置发生变化时(并根据您传递给requestLocationUpdates() 的条件),您的侦听器将通过onLocationChanged() 回调或通过Intent 通知(取决于您传递给requestLocationUpdates() 的参数)。如果您在onLocationChanged() 中进行大量处理,则不应在主线程上运行此方法,而应仅启动后台线程(或将Runnable 发布到后台线程并在后台执行工作线程。

    另一种选择是启动HandlerThread,并将HandlerThread 中的Looper 作为参数提供给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);
    

    【讨论】:

    • 我失去了一个多星期的时间来寻找解决方案,您先生救了我。真是太感谢你了。