当想实现广播接收功能时,因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);
}