简体   繁体   English

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

[英]Android Communication between Broadcast Receiver and MainActivity (Send data to activity)

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 BroadcastReceiver 's onReceive() Method? 我有一个简单的主要活动,必须停止直到收到短信...如何在BroadcastReceiveronReceive()方法中从MainActivity启动方法?

Is there away with Signal and Wait? 有信号和等待吗? Can I pass something with a pending Intent , or how can I implement this communication? 我是否可以通过待处理的Intent传递内容,或者如何实现此通信?

Communication from BroadcastReceiver to Activity is touchy; 从BroadcastReceiver到Activity的通信很敏感; what if the activity is already gone? 如果活动已经消失怎么办?

If I were you I'd set up a new BroadcastReceiver inside the Activity, which would receive a CLOSE message: 如果我是你,我会在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));

Then from the SMS BroadcastReceiver you can send out this action: 然后从SMS BroadcastReceiver您可以发出此操作:

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? 我希望这有帮助?

I had the exact same problem, I tried using intent but i was unsuccessful 我有完全相同的问题,我尝试使用意图,但我没有成功

The easiest way to use it would be using static methods and static variables 使用它的最简单方法是使用静态方法和静态变量

MainActivity.java MainActivity.java

public static void stopsms()
{

/*
some code to stop the activity

*/

}

SMSReceiver.java SMSReceiver.java

at the end call this function 最后调用此函数

MainActivity.stopsms();

It works amazing if your code does not affect when you use static methods and variables. 如果您的代码在使用静态方法和变量时不会影响,那么它的工作效果会很好。 Let me know if you need any help. 如果您需要任何帮助,请告诉我。

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

it's easy, use interface like that: 它很简单,使用这样的界面:

1) in your broadcast receiver create an interface. 1)在你的广播接收器中创建一个接口。

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

and instantiate that interface in your broadcast receiver, use it: 并在广播接收器中实例化该接口,使用它:

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

And in your activity, make it implements your interface 在您的活动中,让它实现您的界面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM