Tuesday, December 22, 2015

android - How to send and receive local broadcast

MainActivity.java

package com.cfsuman.androidtutorials;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.util.Random;


public class MainActivity extends Activity {
    private Context mContext;

    // Initialize a new BroadcastReceiver instance
    private BroadcastReceiver mRandomNumberReceiver
            = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Get the received random number
            int receivedNumber = intent.getIntExtra(
                    "RandomNumber",-1);

            // Display a notification that the broadcast received
            Toast.makeText(
                    context,
                    "Received : " + receivedNumber,
                    Toast.LENGTH_SHORT
            ).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the context
        mContext = getApplicationContext();

        // Register the local broadcast
        LocalBroadcastManager.getInstance(mContext).registerReceiver(
                mRandomNumberReceiver,
                new IntentFilter("BROADCAST_RANDOM_NUMBER")
        );


        // Get the widgets reference from XML layout
        Button button = findViewById(R.id.button);
        TextView textView = findViewById(R.id.textView);


        // Set a click listener for Button widget
        button.setOnClickListener(view -> {
            // Generate a random number
            int randomNumber = new Random().nextInt(500);

            // Initialize a new intent instance
            Intent intent = new Intent("BROADCAST_RANDOM_NUMBER");
            // Put the random number to intent to broadcast it
            intent.putExtra("RandomNumber",randomNumber);

            // Send the broadcast
            LocalBroadcastManager.getInstance(mContext)
                    .sendBroadcast(intent);

            // Update the TextView with random number
            textView.setText("Random number generated : "
                    + randomNumber
                    + "\nApp also broadcast it."
            );
        });
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="#DCDCDC"
    android:padding="24dp">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send Local Broadcast"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif"
        android:textStyle="italic"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>