Android LocalBroadcastManager


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.

  1. What a LocalBroadcastManager is and it's API Definition.
  2. Advantages of LocalBroadcastManager.
  3. 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:

  1. Your application data is kept private as this class works with only loal objects within your application process.
  2. It is more secure due to the fact that it works within your application prcess only.
  3. It is also more efficient than sending a global broadcast through the system.

Demo

Here's the demo for this project.

Android LocalBroadcastManager and IntentService

(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 xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        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 xmlns:android="http://schemas.android.com/apk/res/android"
    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>

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post