广播接收器和MainActivity之间的安卓通信(数据发送到活动)接收器、发送到、通信、数据

2023-09-12 05:00:56 作者:望月叹红尘

我有一个简单的主要活动有停止,直到接收到的短信......我怎么能启动的方法从广播接收器的onReceive()内的MainActivity方法?

I've a simple Main Activity which has to stop till an SMS is received...How can I launch a Method from the MainActivity within the BroadCast Receivers onReceive() Method?

有没有逃脱信号和等待?我可以通过一些与挂起的意图,或者我如何能实现这种交流?

Is there away with Signal and Wait? Can I pass something with a pending Intent, or how can i realise this communication?

非常感谢你的帮助。

推荐答案

从的BroadcastReceiver到活动的通信是敏感的;如果该活动已经走了吗?

Communication from BroadcastReceiver to Activity is touchy; what if the activity is already gone?

如果我是你,我会成立了活动内一个新的BroadcastReceiver,这将收到关闭消息:

If I were you I'd set up a new BroadcastReceiver inside the Activity, which would receive a CLOSE message:

private BroadcastReceiver closeReceiver;
// ...
closeReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {

  //EDIT: receiving parameters
  String value = getIntent().getStringExtra("name"); 
  //... do something with value

  finish();
  }
};
registerReceiver(closeReceiver, new IntentFilter(CLOSE_ACTION));

再从BroadcastReceiver的,你可以发送此操作的短信:

Then from the SMS BroadcastReceiver you can send out this action:

Intent i = new Intent(CLOSE_ACTION);
i.putExtra("name", "value"); //EDIT: this passes a parameter to the receiver
context.sendBroadcast(i);

我希望这可以帮助?

I hope this helps?