Note that there are some explanatory texts on larger screens.

plurals
  1. POAndroid Threading - running a thread from another thread and waiting for a handler message
    primarykey
    data
    text
    <p>My application uses an Executor to create threads to perform tasks.</p> <p>I have a thread which loads and returns bitmaps to the main thread when needed.</p> <p>If the bitmap is not found locally, another thread is used to do the download of the file.</p> <p>All threads create a Looper to ensure that Handlers can be created from that thread (in case it needs to talk to another thread by sending messages to the Handler)</p> <pre><code>public class LooperThread extends Thread { @Override public void run() { Looper.prepare(); super.run(); Looper.loop(); } } </code></pre> <p>The main thread asks Thread-1 to get the bitmap. If the bitmap exists, it is returned successfully to the main thread. If the bitmap doesnt exist, Thread-1 asks Thread-2 to download it. A Handler is created on Thread-1 so Thread-2 can use it to tell Thread-1 when the download is complete.</p> <p>The problem is that Thread-1 completes its execution and exits before the download is complete and so when Thread-2 sends a message through the handler, there is nothing to process the message. </p> <pre><code>final RequestHandler handler = new RequestHandler() { @Override protected void onComplete(Object response) { //This never happens as Thead-1 is already finished when download is complete DownloadCompleteData data = (DownloadCompleteData)response; onDownloadComplete(data.success, data.downloadId, data.filePath); } }; myExecutor.execute(new Runnable() { public void run() { //blocking download call DownloadCompleteData data = download(downloadRequest); //Thread-2 now sends message back to Thread-1 handler.sendMessage(handler.obtainMessage(COMPLETE, data)); } }); </code></pre> <p>I think I need to run an infinite loop in Thread-1 so it can stay alive and keep processing messages until it is interrupted, but I'm not sure how to do this properly.</p> <p>Anyone know the correct way to do it?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload