我想知道是否有办法在 a 的方法中确定活动onReceive(Context context, Intent intent)
活动BroadCastReceiver
?我一开始以为传入的上下文是这样的,后来发现其实是一个ReceiverRestrictedContext
.
我正在尝试执行以下操作,类似于将信息从 a 传递Fragment
到其封装的方式Activity
:
try {
mListener = (MyListenerInterface) (context.getApplicationContext());
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement MyListenerInterface");
}
mListener.onMessageReceived(msg);
每个活动都实现了 MyListenerInterface,并覆盖了 onMessageReceived(msg) 方法,我认为这已经足够了。但是,我在运行和接收广播时收到以下异常:
09-24 22:40:48.706: E/AndroidRuntime(29267): FATAL EXCEPTION: main
09-24 22:40:48.706: E/AndroidRuntime(29267): java.lang.RuntimeException: Unable to start receiver com.test.stuff.Receiver: java.lang.ClassCastException: android.app.ReceiverRestrictedContext@448c8008 must implement MyListenerInterface
09-24 22:40:48.706: E/AndroidRuntime(29267): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2821)
09-24 22:40:48.706: E/AndroidRuntime(29267): at android.app.ActivityThread.access$3200(ActivityThread.java:125)
09-24 22:40:48.706: E/AndroidRuntime(29267): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2083)
09-24 22:40:48.706: E/AndroidRuntime(29267): at android.os.Handler.dispatchMessage(Handler.java:99)
09-24 22:40:48.706: E/AndroidRuntime(29267): at android.os.Looper.loop(Looper.java:123)
09-24 22:40:48.706: E/AndroidRuntime(29267): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-24 22:40:48.706: E/AndroidRuntime(29267): at java.lang.reflect.Method.invokeNative(Native Method)
09-24 22:40:48.706: E/AndroidRuntime(29267): at java.lang.reflect.Method.invoke(Method.java:521)
09-24 22:40:48.706: E/AndroidRuntime(29267): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
09-24 22:40:48.706: E/AndroidRuntime(29267): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-24 22:40:48.706: E/AndroidRuntime(29267): at dalvik.system.NativeStart.main(Native Method)
09-24 22:40:48.706: E/AndroidRuntime(29267): Caused by: java.lang.ClassCastException: android.app.ReceiverRestrictedContext@448c8008 must implement MyListenerInterface
09-24 22:40:48.706: E/AndroidRuntime(29267): at com.test.stuff.Receiver.onReceive(Receiver.java:63)
09-24 22:40:48.706: E/AndroidRuntime(29267): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2810)
09-24 22:40:48.706: E/AndroidRuntime(29267): ... 10 more
在这一点上,我只是在考虑BroadcastReceiver
在每个活动中创建一个内部类并将所需的功能放入其中,但我想知道是否有人知道是否有任何解决上述方案的方法,我只需要一个BroadcastReceiver
具有不同功能的方案基于正在运行的 Activity。