你应该添加一些额外内容,这些附加内容表示来自你正在广播的Intent的调用Activity,然后根据它,写入像SharedPreferences这样的东西.然后在Activity的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();
}
}
然后在每个Activity的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.
}
}
我拥有它的方式,每个Activity都有自己的SharedPreferences数据库,其数据库名称与callingActivity的名称相同.这意味着当您从onResume()读入时,“ThisActivityName”应该与callingActivity相同.但这是主要的想法,你可以修改它.