android 公开静态内部类BroadcastReceiver

原文地址:http://blog.csdn.net/lzg08_08/article/details/8303003

 

用内部类接收广播老是报错,在网上看了下面的东西,很好,解决掉问题了,就mark下来。

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
}
}

内部类需要加上$

<receiver android:name="com.example.progressbar.ProgressBarActivity$mBroadcastReceiver" >
            <intent-filter>
                <action android:name="com.example.progressbar.ProgressBarActivity.mBroadcastReceiver" />
            </intent-filter>
        </receiver>

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

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);
}

posted @ 2013-02-27 17:56  xxzjjcbx  阅读(642)  评论(0编辑  收藏  举报