从主要活动参考处理器对象 [英] Reference handler object from main activity
问题描述
我有一个主活动
类,广播类(广播接收机的子类)和其他几个班。我用的是处理程序
在广播类创建的,有些事情在未来的事情。但是,如果某些情况下,来(用户想要退出应用程序),我想,处理程序
来(被执行prevent)取消。
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 ).
我读了所以很多线就如何取消处理程序
,我知道如何从同一类( Handler.removeCallback(可运行)
, Handler.removeMessages(0)
等)。但我不知道如何从我的活动
取消。 (用户presses退出按钮,如果处理程序将做prevent有些工作我想)。
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 ?
推荐答案
我不知道我完全理解你的问题,但是,如果你想取消处理程序
通过活动,你可以把它放在的onPause
方法:
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);
}
的的onPause
方法被调用时,一个活动即将对用户隐藏的。
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);
}
}
您可以使用里面的广播接收器
和活动
使用类 mHandler 处理器code>。你必须确保你的
广播接收器
类的<strong>不是 静态
内部类的活动
。
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
.
这篇关于从主要活动参考处理器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!