gpt4 book ai didi

java - 从 BroadCastReceiver 更新 UI

转载 作者:行者123 更新时间:2023-12-01 11:36:58 25 4
gpt4 key购买 nike

如何从 BroadCastReceiver 更新主线程。我有一个接收字符串的 BroadCastReceiver,我需要在 MainActivity 上设置 TextView 的文本,当我在 onReceive 方法上执行 findViewById(R.id.textView); 时,它返回 null。

这是我的 MainActivity 的 onCreate。

public class MainActivity extends Activity {

......

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

IntentFilter broadcastFilter = new IntentFilter(ResponseReceiver.LOCAL_ACTION);
receiver = new ResponseReceiver();
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.registerReceiver(receiver, broadcastFilter);

Intent msgIntent = new Intent(MainActivity.this, IntentService.class);
msgIntent.putExtra(StockDataIntentService.PARAM_IN_MSG, getResources().getString(R.string.url));
startService(msgIntent);

}

public class ResponseReceiver extends BroadcastReceiver {

public static final String LOCAL_ACTION = "com.mypackage.ALL_DONE";
private Handler handler;

@Override
public void onReceive(Context context, Intent intent) {
String text =intent.getStringExtra(IntentService.PARAM_OUT_MSG);
TextView txtError = (TextView) findViewById(R.id.error);
}
}

OP question遇到了完全相同的问题,接受的答案解释了使用处理程序等。但是阅读答案的评论解释了 BroadastReceiver runs on the main thread所以没有理由使用处理程序。为什么我无法在 TextView 上设置文本?

最佳答案

when I do findViewById(R.id.textView); on the onReceive method it returns null.

因为目前没有在Activity的onCreate方法中调用setContentView方法来设置当前Activity的布局

因此,在 onCreate 中调用 setContentView 并传递布局,其中 error TextView 可用

关于java - 从 BroadCastReceiver 更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29873175/

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