问题
I have main an Activity class, a broadcast class ( subclass of broadcast receiver ) and few other classes. I use a Handler created in the broadcast class, for some things to do in future. But if some circumstances come ( user wants to exit app ), i want that Handler to cancel (prevent from being executed ).
I read a lot of threads in SO on how to cancel Handlers and I know how to from same class ( Handler.removeCallback (Runnable ), Handler.removeMessages(0) etc ). But I don't know how to cancel it from my Activity. ( user presses exit button, and if handler is going to do some work i want to prevent that ).
So how do I reference that handler object (which is going to execute ) from the Activity class ?
回答1:
I'm not sure I fully understand your question, however, if you want to cancel the Handler via an activity, you can put it in the onPause method:
@Override
public void onPause() {
super.onPause();
handler.removeCallbacks(runnable);
}
The onPause method is called when an activity is about to be hidden from the user.
Having re-read your question, if you mean that you want to access the handler inside a BroadcastReceiver class from your Activity class, then you should make the handler a member variable of your activity.
public class MyActivity extends Activity {
private Handler mHandler = new Handler();
public class BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive (Context context, Intent intent) {
// ... use mHandler in here ....
mHandler.postDelayed(runnable, 1000);
}
}
// ... rest of the code ...
@Override
public void onPause() {
super.onPause();
handler.removeCallbacks(runnable);
}
}
You can use the handler inside your BroadcastReceiver and Activity class using mHandler. You have to make sure that your BroadcastReceiver class is not a static inner class of the Activity.
来源:https://stackoverflow.com/questions/14182846/reference-handler-object-from-main-activity