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

时间:2010-11-09 10:00:50

标签: android android-activity sdk broadcast

我有一个简单的主要活动,必须在收到短​​信之前停止...如何在MainActivity的{​​{1}}方法中BroadcastReceiver启动方法?

是否有信号和等待?我是否可以通过待处理的onReceive()传递内容,或者如何实现此通信?

4 个答案:

答案 0 :(得分:10)

从BroadcastReceiver到Activity的通信很敏感;如果活动已经消失怎么办?

如果我是你,我会在Activity中设置一个新的BroadcastReceiver,它会收到一条CLOSE消息:

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

然后,您可以从SMS BroadcastReceiver发送此操作:

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

我希望这有帮助吗?

答案 1 :(得分:2)

我有完全相同的问题,我尝试使用意图,但我没有成功

使用它的最简单方法是使用静态方法和静态变量

<强> MainActivity.java

public static void stopsms()
{

/*
some code to stop the activity

*/

}

<强> SMSReceiver.java

最后调用此函数

MainActivity.stopsms();

如果您的代码在使用静态方法和变量时不会产生影响,那么效果会很好。如果您需要任何帮助,请告诉我。

答案 2 :(得分:1)

然而,在活动中注册第二个接收器的问题在于它不会像在清单中注册一样持久...因此,虽然此解决方案可能有效,但只有在活动在后台运行时才有效

答案 3 :(得分:0)

很简单,使用这样的界面:

1)在你的广播接收器中创建一个界面。

public interface ChangeListener{
    public void functionWhoSendData(String type);
    public void etc();
}

并在广播接收器中实例化该接口,使用它:

public void onReceive(....
    String data=functionWhereYouReceiveYouData();
    ChangeListener.functionWhoSendData(data);
}

在您的活动中,让它实现您的界面

相关问题