× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Which is the best way to communicate between service and activity?

Xaver Kapeller
Mar 13, 2015
<p>I mostly tend to use <code>LocalBroadcasts</code>. They essentially are like real broadcasts, but only visible to your application. First you have to create a <code>BroadcastReceiver</code> like you would with a normal broadcast:</p> <pre><code>private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(Intent.SOME_ACTION.equals(action)) { // Do your work } } }; </code></pre> <p>You can then register and unregister the <code>BroadcastReceiver</code> like this:</p> <pre><code>@Override public void onResume() { super.onResume(); IntentFilter intentFilter = new IntentFilter(Intent.SOME_ACTION); LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity()); manager.registerReceiver(broadcastReceiver, intentFilter); } @Override public void onPause() { super.onPause(); LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity()); manager.unregisterReceiver(broadcastReceiver); } </code></pre> <p>And finally you can send a broadcast from your <code>Service</code> or anywhere else in your application like this:</p> <pre><code>Intent intent = new Intent(Intent.SOME_ACTION); LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity()); manager.sendBroadcast(intent); </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/23597423/Which%20is%20the%20best%20way%20to%20communicate%20between%20service%20and%20activity?/23597473">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus