Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a number of ways you can do this so I'll just outline 2 ways I would do this.</p> <p>Option 1. use a listener</p> <p>create an interface </p> <pre><code>public interface Listener { public abstract void onEvent(); } </code></pre> <p>in the broadcast receiver create a static reference and setter</p> <pre><code>private static MessageListener mListener = null; @Override public void onReceive(Context context, Intent intent) { //stuff if(mListener != null) mListener.onEvent(); } public static void setListener(Listener l) { mListener = l; } </code></pre> <p>then implement the listener in the Activity</p> <pre><code>class MyActivity implements Listener{ @Override public void onResume(){ //register the listener, should probably unregister in onDestroy BroadCastReceiver.setListener(this); } @Override public void onEvent(){ //do something } } </code></pre> <p>Option 2. use an intent</p> <p>In the broadcast receiver</p> <pre><code>Intent intent = new Intent(); Bundle bundleToSend = new Bundle(); //BUNDLE_EXTRA,DO_SOME_ACTION and ACTION_KEY are just constants so just define them somewhere bundleToSend.putInt(ACTION_KEY, DO_SOME_ACTION); intent.putExtra(BUNDLE_EXTRA, bundleToSend); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent); </code></pre> <p>The flag <code>FLAG_ACTIVITY_SINGLE_TOP</code> will start the activity if its not started or if it is running it will be caught in <code>onNewIntent()</code> so you will need to put some code in both the <code>onCreate()</code> and <code>onNewIntent()</code> to extract the bundle and check for the action.</p> <pre><code>final Bundle bundleReceived = intent.getBundleExtra(BUNDLE_EXTRA); if (bundleReceived.getInt(ACTION_KEY) == DO_SOME_ACTION) { //do something } </code></pre> <p>Option 1 is really only useful for when the broadcast receiver is only going to be receiving when the activity is at the forefront. Option 2 is more versatile and can be used even when the app is not running (eg the broadcast receiver is run in a service started on boot) so that the activity will be started and the action performed no matter the state of the activity.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload