gpt4 book ai didi

java - 在 BroadcastReceiver() 中检索调用上下文

转载 作者:太空宇宙 更新时间:2023-11-03 10:50:14 24 4
gpt4 key购买 nike

我正在尝试显示来自广播接收器的警报对话框 fragment ,但接收器不在将显示该 fragment 的 Activity 中(接收器处理此事件上广播的所有错误,无论它是否是 Activity Activity ).

这是我当前的接收器:

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

但是函数中的上下文参数是它所在的 Activity 的当前上下文,并且会导致运行时非法状态异常,因为该 Activity 不在屏幕上。有没有办法像通过广播一样发送调用函数的上下文?或者还有其他方法可以实现吗?

我目前得到的具体错误是:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

最佳答案

您应该添加额外的内容,说明从您正在广播的 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 是相同的字符串。但这是主要思想,您可以修改它。

关于java - 在 BroadcastReceiver() 中检索调用上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14388257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com