2017-08-26 18 views
-1

我的代碼中出現以下異常。當應用程序長時間處於後臺並可能被操作系統殺死時,就會發生這種情況。之後,當我恢復應用程序時,它拋出以下異常。BroadcastReceiver中發生NullPointerException的原因

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.BroadcastReceiver.onReceive(android.content.Context, android.content.Intent)' on a null object reference 
    at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(Unknown Source) 
    at android.support.v4.content.LocalBroadcastManager.access$000(Unknown Source) 
    at android.support.v4.content.LocalBroadcastManager$1.handleMessage(Unknown Source) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:145) 
    at android.app.ActivityThread.main(ActivityThread.java:6872) 
    at java.lang.reflect.Method.invoke(Method.java) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 

這個異常的可能原因是什麼?我試過註冊一個空的LocalBroadCastReceiver。這不是因爲這個。

感謝

+0

你在manifest.xml中定義了你的廣播嗎?你可以分享你的代碼 – UltimateDevil

+0

它是一個本地廣播接收器。我已經在我的片段中初始化了它,但沒有在Manifest中定義。 – MobileAppDeveloper

+0

好的,你可以分享代碼 – UltimateDevil

回答

2

這是什麼異常的可能原因是什麼?基於the source code to LocalBroadcastManager

,如果這樣看來,你在呼喚registerReceiver(),其中第一個參數(BroadcastReceiver實例)是null。稍後,您打電話sendBroadcast()Intent匹配IntentFilter來自有缺陷的registerReceiver()調用。當主應用程序線程觸發LocalBroadcastManager內部的Handler傳送廣播時,它會失敗,因爲它不能在null上調用onReceive()

FWIW,我剛剛提交了an issue在您打電話給registerReceiver()的時間點檢測到這一點。

+0

謝謝。它有幫助。 – MobileAppDeveloper

相關問題