从主要活动参考处理器对象 [英] Reference handler object from main activity

查看:288
本文介绍了从主要活动参考处理器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主活动类,广播类(广播接收机的子类)和其他几个班。我用的是处理程序在广播类创建的,有些事情在未来的事情。但是,如果某些情况下,来(用户想要退出应用程序),我想,处理程序来(被执行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 。你必须确保你的广播接收器类的<​​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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆