Note that there are some explanatory texts on larger screens.

plurals
  1. POAndroid Threads and Messaging
    primarykey
    data
    text
    <p>I'm working on an Android app that uses uses a background worker thread. I need to be able to send messages to the thread from the activity, but I can't quite figure it out.</p> <p>I have one activity, and one thread to do work in the background. I want to start the thread and be able to send messages (arguments, objects, etc.) to it when needed. I've mastered sending messages from the thread to the activity (by passing the activity's handler to the thread, and using that to send messages), but whenever I attempt to send messages from activity to thread, the app crashes.</p> <p>I've tried following a good 10-12 tutorials that I've found online, all of which seemed to have a different way of doing things, but I still haven't gotten this to work correctly. Could someone please point me in the right direction?</p> <p>An example simple activity:</p> <pre><code>import android.os.Bundle; import android.app.Activity; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savesInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } private void doWork() { Worker worker = new Worker(); worker.start(); worker.handler.sendEmptyMessage(0); } } </code></pre> <p>An example simple thread:</p> <pre><code>import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; public class Worker extends Thread { public Handler handler; public void run() { Looper.prepare(); handler = new Handler() { public void handleMessage(Message msg) { Log.d("Worker.run()", "Got message saying " + msg.what); } }; Looper.loop(); } </code></pre>
    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