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

谁说胖子不能爱 提交于 2019-12-06 03:07:11

问题


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?

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


回答1:


Communication from BroadcastReceiver to Activity is touchy; 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:

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:

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?




回答2:


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

public static void stopsms()
{

/*
some code to stop the activity

*/

}

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.




回答3:


The problem with registering a second receiver within the activity, however, is that it will not be persistent like registering in the manifest... thus, although, this solution may work, will only work if the activity is running in background.




回答4:


it's easy, use interface like that:

1) in your broadcast receiver create an interface.

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



来源:https://stackoverflow.com/questions/4132425/android-communication-between-broadcast-receiver-and-mainactivity-send-data-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!