Android开发中可能被忽视的bug

《Android开发中可能被忽视的bug》

欢迎将您在开发过程中遇到的,容易被忽视的异常情况写到留言区,谢谢

java.lang.IllegalArgumentException

  • 异常:Receiver not registered

  • 出现情况:偶现

  • 问题原因:广播在没有注册的情况下就调用注销广播方法。

  • 问题场景:平时大多动态注册广播,都是把广播注册写在Activity的onCreate方法里面,把注销写在onDestory里面,这样可以保证调用广播注销方法时,该广播一定是被注册过的,但是在其它地方使用,可能由于代码逻辑不够严谨,而出现注销时,广播并没有被注册。

  • 问题衍生:

    1. 如果多次调用注销广播也是会报异常的:

       "Unregistering Receiver " + r+ " that was already unregistered"
      
  • 源码位置:

    1. 文件路径:android.app.ReceiverRestrictedContext.java
     @Override
     public void unregisterReceiver(BroadcastReceiver receiver) {
         if (mPackageInfo != null) {
             IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher(
                     getOuterContext(), receiver);
             try {
                 ActivityManager.getService().unregisterReceiver(rd);
             } catch (RemoteException e) {
                 throw e.rethrowFromSystemServer();
             }
         } else {
             throw new RuntimeException("Not supported in system context");
         }
    
     public IIntentReceiver forgetReceiverDispatcher(Context context,
             BroadcastReceiver r) {
         ...
             if (context == null) {
                 throw new IllegalStateException("Unbinding Receiver " + r
                         + " from Context that is no longer in use: " + context);
             } else {
                 throw new IllegalArgumentException("Receiver not registered: " + r);
             }
         }
     } ```
    
    
    原文作者:奔跑的平头哥
    原文地址: https://www.jianshu.com/p/e98735bda717
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞