RLScott
Newbie
I'm trying to clean up some thread to UI communication code. In this application, a Worker thread is supposed to remaining running for the lifetime of the app, especially through screen rotations or other events that cause the main activity to be destroyed and re-created. I want to avoid memory leaks and null pointer references. The only communication that is necessary is to nudge the main activity with a single integer code. Here is a condensed version of the essentials (I think). Any comments on the approach I have taken would be greatly appreciated.
Code:
public class Main extends Activity {
public static WeakReference<Main> gMain;
public final static MainHandler gMainHand = new MainHandler();
private final static Worker worker = new Worker();
private static class MainHandler extends Handler {
@Override
public void handleMessage(Message msg) {
Main mainNow = gMain.get();
if(mainNow == null)
return;
switch(msg.what)
{
case 42:
/* Do stuff refering to Main variables through mainNow */
break;
}
} //..end of handleMessage
} //..end of MainHandler class
@Override
public void onCreate(Bundle savedInstanceState)
{
gMain = new WeakRefernce<Main>(this);
}
/* some time later:*/ worker.start();
} //..end of Main activity class
public class Worker extends Thread {
public void run()
{
/* at some point */ Main.gMainHand.sendEmptyMessage(42);
}
} //..end of Worker thread class