Monday, November 30, 2015

android - How to send and receive Broadcast

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#d9f1d8"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:padding="15dp"
        />
    <Button
        android:id="@+id/btn_send_broadcast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send Broadcast"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcode;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Random mRandom = new Random();

    private Button mButtonSendBroadcast;
    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Request window feature action bar
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();

        // Get the widgets reference from XML layout
        mButtonSendBroadcast = (Button)findViewById(R.id.btn_send_broadcast);
        mTextView = (TextView) findViewById(R.id.tv);

        // Set a click listener for button
        mButtonSendBroadcast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Generate a new random number
                int nextRandomNumber = mRandom.nextInt(100);
                // Display the random number in TextView
                mTextView.setText("Random Number : " + nextRandomNumber);

                // Initialize a new Intent object
                Intent intent = new Intent();
                // Set an action for the Intent
                intent.setAction("com.cfsuman.RANDOM_NUMBER_INTENT");
                // Put an integer value Intent to broadcast it
                intent.putExtra("RandomNumber",nextRandomNumber);

                /*
                    public abstract void sendBroadcast (Intent intent)
                        Broadcast the given intent to all interested BroadcastReceivers. This call
                        is asynchronous; it returns immediately, and you will continue executing
                        while the receivers are run. No results are propagated from receivers and
                        receivers can not abort the broadcast. If you want to allow receivers to
                        propagate results or abort the broadcast, you must send an ordered
                        broadcast using sendOrderedBroadcast(Intent, String).

                    Parameters
                        intent : The Intent to broadcast; all receivers matching this Intent
                            will receive the broadcast.
                */
                // Finally, send the broadcast
                sendBroadcast(intent);
            }
        });
    }
}
RandomNumberReceiver.java

package com.cfsuman.me.androidcode;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/*
    BroadcastReceiver

        Base class for code that will receive intents sent by sendBroadcast().
        If you don't need to send broadcasts across applications, consider using this class with
        LocalBroadcastManager instead of the more general facilities described below. This will give
        you a much more efficient implementation (no cross-process communication needed) and allow
        you to avoid thinking about any security issues related to other applications being able to
        receive or send your broadcasts.

        You can either dynamically register an instance of this class with Context.registerReceiver()
        or statically publish an implementation through the <receiver> tag in your AndroidManifest.xml.
*/

public class RandomNumberReceiver extends BroadcastReceiver{
    /*
        public abstract void onReceive (Context context, Intent intent)
            This method is called when the BroadcastReceiver is receiving an Intent broadcast.
            During this time you can use the other methods on BroadcastReceiver to view/modify
            the current result values.

        Parameters
            context : The Context in which the receiver is running.
            intent : The Intent being received.
    */
    @Override
    public void onReceive(Context context,Intent intent){
        // Receive the broadcast random number
        int receivedNumber = intent.getIntExtra("RandomNumber",-1);

        // Display the received random number
        Toast.makeText(context,"Broadcast Received : " + receivedNumber,Toast.LENGTH_SHORT).show();
    }
}
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cfsuman.me.androidcode"
    >
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>

        <!--
            Receiver
                The receiver tag declares an BroadcastReceiver class that is available as part of the
                package's application components, allowing the application to receive actions or data
                broadcast by other applications even if it is not currently running.

                Zero or more intent-filter tags can be included inside of a receiver, to specify the
                Intents it will receive. If none are specified, the receiver will only be run when an
                Intent is broadcast that is directed at its specific class name. The receiver tag
                appears as a child tag of the application tag.
        -->
        <!--
            android:name : Required
                name of the class implementing the receiver, deriving from BroadcastReceiver.
        -->
        <receiver android:name=".RandomNumberReceiver">
            <!--
                intent-filter
                    the intent-filter tag is used to construct an IntentFilter object that will be used
                    to determine which component can handle a particular Intent that has been given to
                    the system. It can be used as a child of the activity, receiver and service tags.

                    Zero or more action, category, and/or data tags should be included inside to
                    describe the contents of the filter.

                    The optional label and icon attributes here are used with an activity to supply an
                    alternative description of that activity when it is being started through an Intent
                    matching this filter.
            -->
            <intent-filter>
                <!--
                    Attributes that can be supplied in an AndroidManifest.xml action tag,
                    a child of the intent-filter tag.

                    android:name
                        The name of an action that is handled, using the Java-style naming convention.
                -->
                <action android:name="com.cfsuman.RANDOM_NUMBER_INTENT"/>
            </intent-filter>
        </receiver>
    </application>
</manifest>
More android examples