如何处理Activity里面创建的广播?

时间:2014-09-11 12:20:40

标签: android android-activity broadcastreceiver

我在ActivityActionBarActivity

中创建了一个BroadcastReceiver 像这样


public class MyTabListner extends ActionBarActivity {
.
.
.

    public class AppManagerBroadcast extends BroadcastReceiver {

                @Override
                public void onReceive(Context context, Intent intent) {
                    boolean applicationStatus = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
                    String toastMessage = null;
                    if(intent.getAction().equals("android.intent.action.PACKAGE_INSTALL")){
                        toastMessage = "PACKAGE_INSTALL: "+  intent.getData().toString();


                    }else
                    if(intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")){
                        toastMessage = "PACKAGE_REPLACED: "+  intent.getData().toString() ;

                    }else
                    if(intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")){
                        toastMessage = "PACKAGE_REMOVED: "+  intent.getData().toString();

                    }
                    //Display Toast Message
                    if(toastMessage != null){
                        Toast.makeText(context, toastMessage, Toast.LENGTH_LONG).show();
                    }
                }



            }
.
.
.
}

我在manifest.xml中注册 像这样

 <receiver
            android:name="com.example.activity.MyTabListner$AppManagerBroadcast"
            android:enabled="true" >
            <intent-filter android:priority="1" >
                <action android:name="android.intent.action.PACKAGE_INSTALL" />
                <action android:name="android.intent.action.PACKAGE_REPLACED" />
                <action android:name="android.intent.action.PACKAGE_REMOVED" />
                <data android:scheme="package" />
            </intent-filter>
        </receiver>

但我以这种方式得到了例外。 例外是。

09-11 17:45:46.434: E/AndroidRuntime(23502): FATAL EXCEPTION: main
09-11 17:45:46.434: E/AndroidRuntime(23502): java.lang.RuntimeException: Unable to instantiate receiver com.example.activity.MyTabListner$AppManagerBroadcast: java.lang.InstantiationException: can't instantiate class com.example.activity.MyTabListner$AppManagerBroadcast; no empty constructor

09-11 17:45:46.434: E/AndroidRuntime(23502): Caused by: java.lang.InstantiationException: can't instantiate class com.example.activity.MyTabListner$AppManagerBroadcast; no empty constructor

当我创建了侧面活动然后我成功完全运行我的应用程序但是 我想在活动 非活动中使用此广播接收器。 如何避免这种异常

2 个答案:

答案 0 :(得分:1)

内部类必须是静态类。

更改

public class AppManagerBroadcast extends BroadcastReceiver

public static class AppManagerBroadcast extends BroadcastReceiver

答案 1 :(得分:1)

在我看来你必须将你的内部类声明为静态。目前,内部类必须与外部类的实例一起使用,这可能不是您想要的。