Android LocalBroadcastManager with IntentService Tutorial and Example.
This is an android LocalBroadcastManager tutorial and example. We want to see what LocalBroadcastManager is and how to use with an IntentService.
Video Tutorial
Some people always prefer video tutorials. In that case here’s the video version of this tutorial.
What You Learn in This Tutorial
Here are some of the concpets you will learn in this tutorial.
- What a LocalBroadcastManager is and it’s API Definition.
- Advantages of LocalBroadcastManager.
- How to use LocalBroadcastManager with IntentService.
What is LocalBroadcastManager?
Well LocalBroadcastManager is a helper class that allows us to register for and send broadcasts of Intents to local objects within our process.
Here’s it’s API Definition:
public final class LocalBroadcastManager extends Object java.lang.Object ↳ android.support.v4.content.LocalBroadcastManager
Advantages of LocalBroadcastManager
Here are some of the advantages of LocalBroadcastManager over sending global broadcasts with sendBroadcast(Intent)
method:
- Your application data is kept private as this class works with only loal objects within your application process.
- It is more secure due to the fact that it works within your application prcess only.
- It is also more efficient than sending a global broadcast through the system.
Demo
Here’s the demo for this project.
(a). BroadcastSenderIntentService
This is our IntentService class. We will derive from the android.app.IntentService
and override te onHandleIntent()
method. Inside this method we will simulate heavy task by invoking the sleep()
method of our thread class.
package info.camposha.localbroadcastandintentservice; import android.app.IntentService; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; public class BroadcastSenderIntentService extends IntentService { public BroadcastSenderIntentService() { super("BroadcastSenderIntentService"); } @Override protected void onHandleIntent(Intent intent) { String message = getString(R.string.running); Intent broadcastIntent = new Intent(); broadcastIntent.setAction(MainActivity.MESSAGE_SENT_ACTION); broadcastIntent.putExtra(MainActivity.MESSAGE_EXTRA, message); LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent); try { Thread.sleep(1000); } catch (InterruptedException e) { } message = getString(R.string.finished); broadcastIntent = new Intent(); broadcastIntent.setAction(MainActivity.MESSAGE_SENT_ACTION); broadcastIntent.putExtra(MainActivity.MESSAGE_EXTRA, message); LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent); } }
(b). MainActivity.java
Here’s our main activity. We start by defining several string constants which will be helpful when sending and receiving our intents as they act as identifiers.
package info.camposha.localbroadcastandintentservice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { public static final String MESSAGE_SENT_ACTION = "info.camposha.MESSAGE_RECEIVED_ACTION"; public static final String MESSAGE_EXTRA = "info.camposha.MESSAGE_EXTRA"; private static final String MESSAGE_FROM_SERVICE_KEY = "info.camposha.MESSAGE_FROM_SERVICE_KEY"; private BroadcastReceiver receiver; private TextView serviceMessageView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); serviceMessageView = findViewById(R.id.service_message_textview); if (savedInstanceState != null) { serviceMessageView.setText(savedInstanceState.getString(MESSAGE_FROM_SERVICE_KEY)); }else{ serviceMessageView.setText("Null"); } } @Override protected void onResume() { super.onResume(); receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); String message = bundle.getString(MESSAGE_EXTRA); serviceMessageView.setText(message); } }; LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter(MESSAGE_SENT_ACTION)); } @Override protected void onPause() { super.onPause(); if (receiver != null) { LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); receiver = null; } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(MESSAGE_FROM_SERVICE_KEY, serviceMessageView.getText().toString()); } public void onStartServiceClicked(View view) { startService(new Intent(this, BroadcastSenderIntentService.class)); } }
activity_main.xml
Here’s our main activity’s layout. We have textview and button here.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout android_layout_width="match_parent" android_layout_height="match_parent" tools_context=".MainActivity"> <TextView android_id="@+id/headerLabel" android_layout_width="wrap_content" android_layout_height="wrap_content" android_layout_alignParentTop="true" android_layout_centerHorizontal="true" android_fontFamily="casual" android_text="LocalBroadcastReceiver" android_textAllCaps="true" android_textSize="24sp" android_textStyle="bold" /> <LinearLayout android_layout_width="wrap_content" android_layout_height="wrap_content" android_layout_centerHorizontal="true" android_layout_centerVertical="true" android_gravity="center" android_orientation="vertical" > <TextView android_id="@+id/textView1" android_layout_width="wrap_content" android_layout_height="wrap_content" android_text="@string/service_status" android_textSize="16dp" /> <TextView android_id="@+id/service_message_textview" android_layout_width="wrap_content" android_layout_height="wrap_content" android_text="@string/not_running" android_textSize="16dp" /> </LinearLayout> <Button android_id="@+id/button1" android_onClick="onStartServiceClicked" android_text="@string/start_service" android_layout_width="wrap_content" android_layout_height="wrap_content" android_layout_alignParentBottom="true" android_layout_centerHorizontal="true" android_layout_marginBottom="12dp" android_fontFamily="serif-monospace" /> </RelativeLayout>
AndroidManifest.xml
In our android manifes you have to make sure that we register the service. Here’s mine:
<?xml version="1.0" encoding="utf-8"?> <manifest package="info.camposha.localbroadcastandintentservice"> <application android_allowBackup="true" android_icon="@mipmap/ic_launcher" android_label="@string/app_name" android_roundIcon="@mipmap/ic_launcher_round" android_supportsRtl="true" android_theme="@style/AppTheme"> <activity android_name=".MainActivity"> <intent-filter> <action android_name="android.intent.action.MAIN" /> <category android_name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android_name=".BroadcastSenderIntentService" /> </application> </manifest>