On May 28, 4:40 pm, Streets Of Boston <[email protected]> wrote:
> Is it safe to cache a Handler (in a static variable)?
It should be OK, from my reading of the code. It keeps a reference to
the current threads looper, but that should exist for as long as the
process does anyway.
I *think* you'd code it up like this, although I haven't actually done
it :)
public class MyActivity extends Activity implements Handler.Callback {
static Object sHandlerLock = new Object();
static Handler sHandler;
public void handleMessage(Message msg) { .... }
public void onCreate() {
synchronized (MyActivity.sHandlerLock) {
sHandler = new Handler(this);
}
}
public void onDestroy() { // Could be onStop as well I think
synchronized (MyActivity.sHandlerLock) {
sHandler = null;
}
if (isFinishing) myThread.interrupt(); // tell the worker thread
to shut down.
}
}
then in your thread:
public void run() {
// ... do some work ....
synchronized (MyActivity.sHandlerLock) {
if (MyActivity.sHandler != null) MyActivity.sHandler.sendMessage
(whatever);
}
}
You have to lock because otherwise you could test sHandler against
null to see if the activity is still around to receive your status
update, find it's set, then the main thread destroys the activity
resulting in your worker thread crashing when it tries to send a
message to the main thread.
Note the call to interrupt() in onDestroy. You don't want your worker
thread to hang around doing stuff when the user is actually done with
your app. I'm not 100% sure this is correct though - the javadoc for
isFinishing() is kinda vague. Eg I don't know if using the home button
counts as "finishing" an activity or just task switching away.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en
-~----------~----~----~----~------~----~------~--~---