OnLocationChanged callback is executed in which thread? The main user interface thread?

When this callback is executed in my application, I did a bit of work (reading and writing to SQL db via ORM lib and a series of calculations based on distance). Naturally, I'm not concerned about blocking the main thread of the user interface, so I tried (unsuccessfully) to find out if this is the thread on which the callback is being executed. If so, I intend to do all of the above work on AsyncTask invoked on the callback. This AsyncTask will receive events from two separate activity classes. (Response to user input, etc.)

Most of the discussion I found around this callback seems to be based on people trying to change the thread that the callback actually received. It makes no sense to me. Of course, the platform defines the context of this callback, and the sensible thing to do when it is received is to upload any serious work to another thread for which AsyncTask seems appropriate.

If someone could describe the successful template they used here, that would be really helpful.

+7
source share
1 answer

According to the help documentation for Android LocationManager :

The calling thread must be a Looper thread, such as the main thread causing the activity.

This means that the thread that initiates the callback must be the main thread or the Looper tag.

I found the best way to handle this is to register the OnLocationChanged receiver on the main topic. Then in my callback I will create a Runnable to send to the background thread, where I will perform any lengthy tasks (e.g. 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. //... } }); } 
+7
source

All Articles