java - 从 BroadCastReceiver 更新 UI

标签 java android broadcastreceiver

如何从 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/

相关文章:

android - 如何创建即使在手机重启后也始终运行的通知?

java - 更新/删除证书链: Cannot assign the key to the given alias

java - 如何在javadoc中添加对方法参数的引用?

javascript - 正则表达式不适用于 jsp java 中的数字

java - maven 和 gwt 的 Log4j 问题 : org. apache.log4j.XAppender 对象不可分配

android - 手机关机的时间戳?

Android暂停和恢复上传

android - 如何在android中的编辑文本中添加 "+91"和删除 "+91"?

java - BaseAdaper 中的广播接收器

android - 成功建立 Wifi 连接后,使用 WifiManager.NETWORK_STATE_CHANGED_ACTION 接收广播是否安全?