从BroadCastReceiver

时间:2015-04-26 02:55:36

标签: 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);
      }
  }

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

1 个答案:

答案 0 :(得分:1)

  

当我找到ViewById(R.id.textView);关于onReceive方法吧   返回null。

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

所以,通过传递setContentView TextView可用

的布局来调用onCreate中的error