Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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

like image 499
NonoNever Avatar asked Nov 09 '10 10:11

NonoNever


1 Answers

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?

like image 160
Emmanuel Avatar answered Oct 02 '22 06:10

Emmanuel