Android Communications Between Broadcast Receiver and MainActivity (Data Transfer to Action)

I have a simple main activity, which should stop before receiving SMS ... How to start a method from MainActivityin a method BroadcastReceiver onReceive()?

Do away with a signal and wait? Can I convey something with a wait Intent, or how can I implement this message?

+5
source share
4 answers

Communication from BroadcastReceiver to Activity is cracky; what if activity has already disappeared?

If I were you, I would install a new BroadcastReceiver inside an Activity that 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));

SMS BroadcastReceiver :

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

, ?

+10

, ,

-

MainActivity.java

public static void stopsms()
{

/*
some code to stop the activity

*/

}

SMSReceiver.java

MainActivity.stopsms();

, . , .

+2

, , ... , , , .

+1

, :

1) create an interface in your broadcast receiver.

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

and create this interface in your broadcast receiver, use it:

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

And in your activity do it by implementing your interface

0
source

All Articles