android内部类broadcastreceiver,android 公开静态内部类BroadcastReceiver
當(dāng)想實(shí)現(xiàn)廣播接收功能時,因java ?是單繼承,所以一般一個類都會extends Activity,所以會想到內(nèi)部類來extends BroadcastReceiver,這中間可能會出現(xiàn)兩種異常
1:java.lang.RuntimeException: Unable to instantiate
receiver com.example.progressbar.ProgressBarActivity$mBroadcastReceiver:
java.lang.InstantiationException: com.example.progressbar.ProgressBarActivity$mBroadcastReceiver
這是因?yàn)閮?nèi)部類需要寫成靜態(tài)的,即static
static?class mBroadcastReceiver extends BroadcastReceiver {
//必須為靜態(tài)公開的(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
這是因?yàn)樾枰獙⒋祟悓懗蓀ublic ,若沒寫默認(rèn)為protected的,則會出現(xiàn)access to class not allowed
正確的為:
public static?class mBroadcastReceiver extends BroadcastReceiver {
//必須為靜態(tài)公開的(public static)
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
}
}
內(nèi)部類需要加上$
當(dāng)然還有另一種方法即實(shí)現(xiàn)其一個實(shí)例
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
}
};
然后就是注冊和注銷
在onCreate() 或onResume()中調(diào)用registerBoradcastReceiver()
public void registerBoradcastReceiver() {
IntentFilter myIntentFilter = new IntentFilter();
myIntentFilter.addAction(ACTION_NAME);
// 注冊廣播
registerReceiver(mBroadcastReceiver, myIntentFilter);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mBroadcastReceiver);
}
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的android内部类broadcastreceiver,android 公开静态内部类BroadcastReceiver的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android 信鸽 自动重启,Andr
- 下一篇: ajax success返回 .net,