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

Use LocalBroadcastManager for Activity-Service Communication

Aviral Dasgupta
Mar 03, 2016
<p>One easy way to implement activity-service communication is through a <strong>LocalBroadcastManager</strong>.</p> <p>In your service, you want to do:</p> <pre>Intent intent = new Intent(<span style="color:#6a8759">"eventName"</span>)<span style="color:#cc7832">;</span><span style="color:#808080"> </span>intent.putExtra(<span style="color:#6a8759">"data"</span><span style="color:#cc7832">, </span><span style="color:#6a8759">"data"</span>)<span style="color:#cc7832">; // You can add additional data to the intent... </span>LocalBroadcastManager.getInstance(<span style="color:#cc7832">this</span>).sendBroadcast(intent);<span style="color:#cc7832"> </span></pre> <p>And in your activity:</p> <pre>LocalBroadcastManager.getInstance(<span style="color:#cc7832">this</span>).registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context<span style="color:#cc7832">, </span>Intent intent) <strong>{</strong><span style="color:#808080"> </span><span style="color:#808080"> </span>String data = intent.getStringExtra(<span style="color:#6a8759">"data"</span>)<span style="color:#cc7832">; // ... and retrieve that data here.</span><span style="color:#cc7832"> </span><span style="color:#cc7832"> </span><strong>} </strong>}<span style="color:#cc7832">, </span>new IntentFilter(<span style="color:#6a8759">"eventName"</span>))<span style="color:#cc7832">;</span></pre>

Get New Tutorials Delivered to Your Inbox

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

comments powered by Disqus