在单独的线程中的requestLocationUpdates() [英] requestLocationUpdates() in separate Thread

查看:631
本文介绍了在单独的线程中的requestLocationUpdates()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将requestLocationUpdates()放在单独的线程中,以免它阻塞我的其余应用程序(它将在大多数时间运行).最好的方法是什么?

I need requestLocationUpdates() to be in a separate Thread, in order to not have it blocking the rest of my application (it will run most of the time). What is the best way to do it?

推荐答案

当您呼叫requestLocationUpdates()时,这仅表示您希望在用户位置更改时被回叫.该调用不需要花费大量时间,并且可以在主线程上进行.

When you call requestLocationUpdates() this just indicates that you want to be called back when the user's location changes. This call doesn't take a significant amount of time and can be made on the main thread.

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

When the user's location changes (and based on the criteria you pass to requestLocationUpdates()) your listener will be called back via onLocationChanged() or notified via Intent (depending on which parameters you pass to requestLocationUpdates()). If you do a lot of processing in onLocationChanged() then you shouldn't run this method on the main thread, but you should just start a background thread (or post a Runnable to a background thread and do your work on the background thread.

另一种选择是启动HandlerThread并将Looper中的Looper作为参数提供给requestLocationUpdates().在这种情况下,对onLocationChanged()的回调将在HandlerThread上进行.看起来像这样:

Another option is to start a HandlerThread and provide the Looper from the HandlerThread as a parameter to requestLocationUpdates(). In that case, the callbacks to onLocationChanged() will be made on the HandlerThread. This looks something like this:

    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);

这篇关于在单独的线程中的requestLocationUpdates()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆