我在动态注册 BroacasrReceiver 时遇到问题CallReceiver
。当触发onReceive
方法时,CallReceiver
会抛出致命异常。
...
private boolean isCRRegistered = false;
public int onStartCommand (Intent intent, int flags, int startId) {
if(!isCRRegistered) {
IntentFilter filter2 = new IntentFilter("android.intent.action.PHONE_STATE");
CallReceiver mCallReceiver = new CallReceiver();
registerReceiver(mCallReceiver, filter2);
//registering some listener
mCallReceiver.registerListener(this);
}
}
注销:
if(isCRRegistered) {
unregisterReceiver (mCallReceiver);
}
日志猫:
02-04 14:41:50.286: E/AndroidRuntime(28328): FATAL EXCEPTION: main
02-04 14:41:50.286: E/AndroidRuntime(28328): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.PHONE_STATE flg=0x20000000 (has extras) } in com.kris.intellignetringer.CallReceiver@448162b8
02-04 14:41:50.286: E/AndroidRuntime(28328): at android.app.ActivityThread$PackageInfo$ReceiverDispatcher$Args.run(ActivityThread.java:934)
02-04 14:41:50.286: E/AndroidRuntime(28328): at android.os.Handler.handleCallback(Handler.java:587)
02-04 14:41:50.286: E/AndroidRuntime(28328): at android.os.Handler.dispatchMessage(Handler.java:92)
02-04 14:41:50.286: E/AndroidRuntime(28328): at android.os.Looper.loop(Looper.java:143)
02-04 14:41:50.286: E/AndroidRuntime(28328): at android.app.ActivityThread.main(ActivityThread.java:4914)
02-04 14:41:50.286: E/AndroidRuntime(28328): at java.lang.reflect.Method.invokeNative(Native Method)
02-04 14:41:50.286: E/AndroidRuntime(28328): at java.lang.reflect.Method.invoke(Method.java:521)
02-04 14:41:50.286: E/AndroidRuntime(28328): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
02-04 14:41:50.286: E/AndroidRuntime(28328): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
02-04 14:41:50.286: E/AndroidRuntime(28328): at dalvik.system.NativeStart.main(Native Method)
02-04 14:41:50.286: E/AndroidRuntime(28328): Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.kris.intellignetringer.ScreenReceiver@44816d60
02-04 14:41:50.286: E/AndroidRuntime(28328): at android.app.ActivityThread$PackageInfo.forgetReceiverDispatcher(ActivityThread.java:812)
02-04 14:41:50.286: E/AndroidRuntime(28328): at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:822)
02-04 14:41:50.286: E/AndroidRuntime(28328): at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:331)
02-04 14:41:50.286: E/AndroidRuntime(28328): at com.kris.intellignetringer.StateChecker.serviceDestroy(StateChecker.java:126)
02-04 14:41:50.286: E/AndroidRuntime(28328): at com.kris.intellignetringer.StateChecker.onPhoneStateChange(StateChecker.java:36)
02-04 14:41:50.286: E/AndroidRuntime(28328): at com.kris.intellignetringer.CallReceiver.onReceive(CallReceiver.java:50)
02-04 14:41:50.286: E/AndroidRuntime(28328): at android.app.ActivityThread$PackageInfo$ReceiverDispatcher$Args.run(ActivityThread.java:917)
02-04 14:41:50.286: E/AndroidRuntime(28328): ... 9 more