Reputation: 837
I have an Android app with three threads, the main thread and two worker threads. The threads need to communicate with each other regularly.
I had originally gone about doing this in a horrible way that everyone here would yell at me for. I saved instances of the thread in each thread and called methods of the class from the other threads if a thread needed that functionality. It worked, but I knew it wasn't right.
Since that was wrong, I went back through and changed each instance of a thread to an instance of the thread's handler, and each thread function call I replaced with a handler.sendMessage call.
Now the program doesn't work. It just freezes, and I have no idea whats going on. When using the debug perspective, I step through the main thread but all I get is the function
boolean hasMessages(Handler h, int what, Object object)
{
...
}
from the MessageQueue. The other threads are looping in their run() function which doesn't do anything exciting. None of my logs are printing. I am at a loss for what is happening and I don't know what steps I should take next to continue debugging it. All I changed was adding handlers and sending messages. Can you guys suggest any next steps I should take for debugging?
Edit: Here is some code, I'm having no luck
Main Activity:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionStatusTextView = (TextView) findViewById(R.id.connectionStatus);
imageView = (ImageView) findViewById(R.id.imageView);
commandView = (TextView)findViewById(R.id.commandView);
focusView = (TextView)findViewById(R.id.focusView);
mApplication = ((myApplication) this.getApplication());
ConnectedThread connectedThread = new ConnectedThread(mHandler, mApplication);
VoiceRecognitionThread voiceThread = new VoiceRecognitionThread(mApplication, this);
connectedThread.setHandlers(mHandler, voiceThread.getHandler());
voiceThread.setHandlers(mHandler, connectedThread.getHandler());
connectedThread.start();
voiceThread.start();
}
ConnectedThread and VoiceRecognitionThread both extend HandlerThread. They both create a class level Handler which handles messages sent to those threads. getHandler returns a reference to those handlers.
Upvotes: 0
Views: 1203
Reputation: 5867
Just use a HandlerThread and feed it with messages via its handler object:
HandlerThread thread1 = new HandlerThread("Thread Name");
thread1.start();
handler1 = new MyHandler(thread1.getLooper());
// pass message for thread 1
handler1.sendmessage()
// and same for threads 2 and 3
Note that if you plan your threads to be long running, a far better solution would be to use an IntentService.
IntentService are services and, as such, are by far less susceptible to Android reclamation then resources gets low.
Upvotes: 1