Receiver无法解决变量Android错误

时间:2014-05-14 12:16:01

标签: android broadcastreceiver

我是Android的初学者。我正在尝试动态注册和取消注册接收器。但我在代码中遇到错误。我试着像这样注册和取消注册接收器:

注册

this.registerReceiver(receiver, new IntentFilter("android.intent.action.TIME_TICK"));

注销:

this.unregisterReceiver(receiver);
        Toast.makeText(this, "UnRegistered broadcast receiver", Toast.LENGTH_SHORT)

但是在两个陈述中它都给出了同样的错误:

  

接收器无法解析为变量

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

在注册之前定义并初始化接收器。

您可以定义来自onCreat

/**
     * the BroadcastReceiver definition
     */
BroadcastReceiver receiver;

而不是在onCreat(注册前)中将其初始化为例:

// the BroadcastReceiver initialization
broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
// do something when your receiver is called
}
};

然后你可以注册并取消注册......