Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As promised the easy way: you basically send the broadcast synchroniously and if there is a receiver, you'll set a static flag in your service class, which let's the service know it's already handled:</p> <pre><code>public class TestService extends IntentService { public volatile static boolean isHandled = false; public static final String INTENT_ACTION_HANDLEGCM = "com.intentexample.gcm"; ... @Override protected void onHandleIntent(Intent intent) { ... Intent toActivityIntent = new Intent(); toActivityIntent.setAction(INTENT_ACTION_HANDLEGCM); // toActivity: put other stuff into extras, which you need to update your UI TestService.isHandled = false; LocalBroadcastManager.getInstance(this).sendBroadcastSync(toActivityIntent); if (!TestService.isHandled) { // post your notification to the notification bar } } } </code></pre> <p>and register &amp; unregister the broadcast receiver with the intent filter for INTENT_ACTION_HANDLEGCM in your activities onResume and onPause (remember to use LocalBroadcastManager)</p> <pre><code>public class MyActivity extends Activity { BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { TestService.isHandled = true; // update the UI } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onResume() { super.onResume(); LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter(TestService.INTENT_ACTION_HANDLEGCM)); } @Override protected void onPause() { super.onPause(); LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); } } </code></pre> <p>NOTE: this code is untested, but should give you the general idea. I personally wouldn't do it this way except:</p> <ul> <li>under time pressure</li> <li>the feature is a minor feature and won't be extended anytime soon.</li> </ul>
 

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