Reputation: 239
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.
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.
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?
An example simple activity:
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);
}
}
An example simple thread:
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();
}
Upvotes: 0
Views: 1345
Reputation: 161
You have to read how to use and that for is Looper first and don't forget to stop looper at the end Goodluck
public class Worker extends Thread {
public Handler handler;
@Override
public run() {
Looper.prepare();
//initialization will take a little time you if you want to send message check if handler != null
handler = new Handler() {
public void handleMessage(Message msg) {
Log.d("Worker.run()", "Got message saying " + msg.what);
}
};
Looper.loop();
}
public void sendMessage(Message m)
{
while(handler == null);
handler.sendMessages(m);
}
Upvotes: 1