Android開發中可能被忽視的bug

java.lang.IllegalArgumentException

  • 異常:Receiver not registeredjava

  • 出現狀況:偶現android

  • 問題緣由:廣播在沒有註冊的狀況下就調用註銷廣播方法。bash

  • 問題場景:平時大多動態註冊廣播,都是把廣播註冊寫在Activity的onCreate方法裏面,把註銷寫在onDestory裏面,這樣能夠保證調用廣播註銷方法時,該廣播必定是被註冊過的,可是在其它地方使用,可能因爲代碼邏輯不夠嚴謹,而出現註銷時,廣播並無被註冊。app

  • 問題衍生:ide

    1. 若是屢次調用註銷廣播也是會報異常的:spa

      "Unregistering Receiver " + r+ " that was already unregistered"
      複製代碼
  • 源碼位置:code

    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 來源:簡書 簡書著做權歸做者全部,任何形式的轉載都請聯繫做者得到受權並註明出處。
相關文章
相關標籤/搜索