4

我試圖從廣播接收器中顯示一個警報對話框片段,但接收器不在將顯示片段的活動中(接收器處理在此事件上廣播的所有錯誤,無論是否是主動活動)。檢索廣播接收器中的調用上下文()

這是我目前的接收器:

private BroadcastReceiver mHttpPostReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
       if (intent.getStringExtra("Error") != null) { // error occurred 
         // called from a fragment in another activity 
         NetworkError.show(((Activity) context).getFragmentManager(), error); 
       } 
     } 
};   

但在功能上下文參數是它是在並導致運行時非法狀態異常,因爲這個活動是不是在屏幕上活動的當前上下文。有沒有辦法通過廣播發送調用函數的上下文?或者還有另一種方法我應該實施這個?

我目前得到特定的錯誤是:

java.lang.IllegalStateException:不能

的onSaveInstanceState

回答

1

您應該添加附加信息,說您從Intent呼叫Activity您是bcroadcas丁,然後基於此,寫入像SharedPreferences。然後在活動的onResume()中,檢查首選項的密鑰是否包含消息,然後更新UI。

@Override 
public void onReceive(Context context, Intent intent) { 
    if (intent.getStringExtra("Error") != null) { 
    String callingActivity = intent.getStringExtra ("CallingActivity"); 
    if (callingActivity != null); 
    context.getSharedPreferences (callingActivity, Context.MODE_PRIVATE).edit().putString ("errorMessage", "You have an error").commit(); 
    } 
} 

然後在每個活動的onResume()

@Override 
protected void onResume() 
{ 
    super.onResume(); 
    String errorMsg =context.getSharedPreferences ("ThisActivityName", Context.MODE_PRIVATE).getString ("error"); 
    if (errorMsg.equals ("You have an error")){ 
    //update fragment code here. 
    //set SharedPreference errorMessage key to hold something else. 
    } 
} 

的方式我有它,每個活動都有自己的SharedPreferences的數據庫,數據庫名稱相同的名稱callingActivity。這意味着當您從onResume()讀入時,"ThisActivityName"應該與callingActivity相同。但這是主要想法,你可以修改這個。

+0

這會工作,但調用這一個的活動不會暫停。調用活動發送廣播然後空閒,上面的方法現在創建一個SharedPreferences條目,但調用函數以後不會到達onResume方法。 – user1988523

+0

@ user1988523你是什麼意思* idles *?你的意思是Activity的'onPause()'沒有被調用? –

+0

這似乎是這種情況。我在調用函數的onPause()和onResume()中設置了斷點,但它們從未到達。在此期間,調用片段創建一個線程,該線程發送廣播,然後由另一個活動中的上述函數接收廣播(原始片段在發送廣播後不做任何操作)。 – user1988523

0

我做了這樣的事情裏面的onReceive方法後,執行此操作:

if (context instanceof LoginActivity) { 
     switchLoginFields((LoginActivity) context, isConnected); 
    } else if (context instanceof ReceiptActivity || context instanceof AmountActivity) { 
     showArelt(context, isConnected); 
    } 
+0

我需要使用廣播發送者的上下文,而不是上述函數中的上下文(儘管這會在我有這個時有用)。 – user1988523