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);
               }
      }
};        

ただし、関数の context パラメータは、それが含まれるアクティビティの現在のコンテキストであり、このアクティビティが画面上にないため、ランタイムの不正な状態例外を引き起こします。ブロードキャストのように、呼び出し元の関数のコンテキストを送信する方法はありますか? または、これを実装する必要がある別の方法はありますか?

現在発生している特定のエラーは次のとおりです。

java.lang.IllegalStateException: onSaveInstanceState の後にこのアクションを実行できません

4

2 に答える 2

1

Activityブロードキャストしているからの呼び出しを示すエクストラを追加する必要Intentがあります。次に、それに基づいて、 のようなものに書き込みます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。しかし、これは主なアイデアであり、これを変更できます。

于 2013-01-17T21:30:16.900 に答える
0

onReceiveメソッド内で次のようなものを作成しました。

    if (context instanceof LoginActivity) {
        switchLoginFields((LoginActivity) context, isConnected);
    } else if (context instanceof ReceiptActivity || context instanceof AmountActivity) {
        showArelt(context, isConnected);
    }
于 2013-01-17T21:17:56.197 に答える