android内部类broadcastreceiver,android 公开静态内部类BroadcastReceiver

当想实现广播接收功能时,因java  是单继承,所以一般一个类都会extends Activity,所以会想到内部类来extends BroadcastReceiver,这中间可能会出现两种异常

1:java.lang.RuntimeException: Unable to instantiate

receiver com.example.progressbar.ProgressBarActivity$mBroadcastReceiver:

java.lang.InstantiationException: com.example.progressbar.ProgressBarActivity$mBroadcastReceiver

这是因为内部类需要写成静态的,即static

static class mBroadcastReceiver extends BroadcastReceiver {

//必须为静态公开的(public static)

@Override

public void onReceive(Context context, Intent intent) {

// TODO Auto-generated method stub

}

}

2: java.lang.RuntimeException: Unable to instantiate

receiver com.example.progressbar.ProgressBarActivity$mBroadcastReceiver:

java.lang.IllegalAccessException: access to class not allowed

这是因为需要将此类写成public ,若没写默认为protected的,则会出现access to class not allowed

正确的为:

public static class mBroadcastReceiver extends BroadcastReceiver {

//必须为静态公开的(public static)

@Override

public void onReceive(Context context, Intent intent) {

// TODO Auto-generated method stub

}

}

内部类需要加上$

当然还有另一种方法即实现其一个实例

private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

}

};

然后就是注册和注销

在onCreate() 或onResume()中调用registerBoradcastReceiver()

public void registerBoradcastReceiver() {

IntentFilter myIntentFilter = new IntentFilter();

myIntentFilter.addAction(ACTION_NAME);

// 注册广播

registerReceiver(mBroadcastReceiver, myIntentFilter);

}

@Override

public void onDestroy() {

super.onDestroy();

unregisterReceiver(mBroadcastReceiver);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值