onLocationChanged回调做什么主题?主UI线程?做什么、线程、回调、主题

2023-09-07 04:41:26 作者:心╰→比柠檬酸

在这个回调是在我的应用程序,我有相当多的工作要做(阅读及放大器;通过ORM lib和一些基于距离的计算写SQL数据库)。当然,我很担心不阻塞主UI线程,所以我一直在尝试(失败),以找出是否这是在其上回调做的线程。如果是,我打算做一个AsyncTask的所有上述工作时触发回调而成。同样的AsyncTask将接收事件从2个独立的活动课也是如此。 (响应用户输入等。)

When this callback is made in my app, I have quite a bit work to do (reading & writing to SQL db through an ORM lib and a number of distance based calculations). Naturally I am concerned about not blocking the main UI thread so I've been trying (unsuccessfully) to find out if this is the thread on which the callback is made. If it is, I'm intending to do all the afore-mentioned work on an AsyncTask triggered when the callback is made. This same AsyncTask will receive events from 2 separate activity classes as well. (Responding to user input etc..)

很多我已经解决这个回调中的讨论似乎是基于各地的人们试图改变在其实际收到回调的线程。这是没有意义的我。当然,该平台确定回调的背景和明智的事情,当它接收到的是卸载任何严肃的工作到另一个线程,为此AsyncTask的似乎是适当的。

A lot of the discussion I have found around this callback seems to be based around people trying to change the thread on which the callback is actually received. This makes no sense to me. Surely the platform determines the context of this callback and the sensible thing to do when it's received is offload any serious work onto another thread, for which AsyncTask seems appropriate.

如果任何人都可以勾勒出一个成功的模式,他们在这里用这将是非常有用的。

If anyone can outline a successful pattern they've used here it would be really useful.

推荐答案

据为LocationManager:

调用线程必须是环线等主线程   调用活动。

The calling thread must be a Looper thread such as the main thread of the calling Activity.

这意味着初始化回调线程必须是主线程或尺蠖主题。

This means that the Thread that initializes the callback must be the main Thread or a Looper Thread.

我发现处理这一点的最好办法就是注册一个 OnLocationChanged 接收器上的主线程。然后,在我的回调我将创建一个Runnable发送到后台线程,我会执行任何长时间运行的任务(如写入数据库)。

I've found the best way to handle this is to register an OnLocationChanged receiver on the main Thread. Then, in my callback I'll create a Runnable to send to a background Thread where I'll perform any long-running tasks (like writing to the database).

ExecutorService mThreadPool = Executors.newSingleThreadExecutor();

@Override
public void onLocationChanged(Location location) {
    mThreadPool.execute(new Runnable() {
        @Override
        public void run() {
            // Perform your long-running tasks here.
            //...
        }
    });
}
 
精彩推荐
图片推荐