Skip to main content

android - How to send and receive Broadcast


<?xml version="1.0" encoding="utf-8"?>
        android:text="Send Broadcast"


import android.content.Context;
import android.content.Intent;
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;

    protected void onCreate(Bundle savedInstanceState) {
        // Request window feature action bar

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

        // Get the widgets reference from XML layout
        mButtonSendBroadcast = (Button)findViewById(;
        mTextView = (TextView) findViewById(;

        // Set a click listener for button
        mButtonSendBroadcast.setOnClickListener(new View.OnClickListener() {
            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
                // Put an integer value Intent to broadcast it

                    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).

                        intent : The Intent to broadcast; all receivers matching this Intent
                            will receive the broadcast.
                // Finally, send the broadcast


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


        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.

            context : The Context in which the receiver is running.
            intent : The Intent being received.
    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();

<?xml version="1.0" encoding="utf-8"?>
        <activity android:name=".MainActivity" >
                <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />

                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">
                    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.
                    Attributes that can be supplied in an AndroidManifest.xml action tag,
                    a child of the intent-filter tag.

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

Popular posts from this blog

How to use NumberPicker in Android

Table of contentsNumberPicker ExamplesetOnValueChangedListeneronValueChange()setWrapSelectorWheel()setMinValue()setMinValue()setMaxValue()NumberPicker with String ArraysetDisplayedValues()String Array1. NumberPicker Example activity_main.xml <RelativeLayout xmlns:android="" xmlns:tools="" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity" android:background="#ffffff" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25dp" android:text="Select a number..." /> <NumberPicker android:id="@+id/np" …

TextView new line (multiline) in android

TextView new line (multiline) TextView display text on android app. by default, TextView show text on a single line, and if it is long then TextView take more lines to display its text. android developers can generate a new line on TextView both programmatically and syntactically. android developers can make a multiline TextView without splitting text to multiline by android:minLines attribute.

the following android example code demonstrate us how can we syntactically create a new line on TextView widget by xml layout file and string resource file.

the simplest way to create a new line on TextView is android:text attribute. android:text attribute allow us to display text on android app. we can add a simple '\n' to TextView text where we want to start a new line. in this way we can create a multiline TextView widget in android app. we can assign android:text attribute value by this way android:text="Line1 \n Line2 \n Line3" for a TextView widget. this value will…

How to change TextView font size in android

TextView font size TextView widget display text on android application. we can set or change TextView font size statically by declarative syntax in xml layout file or programmatically at run time in java file. even we can use an xml file source to define font size.

the following example code demonstrate us how can we define TextView font size in xml layout file and how can we uses dimens.xml to reference font size. in this example we did not changes any coding in java file, so here we only include the layout xml file and dimens.xml file. activity_main.xml <LinearLayout xmlns:android="" xmlns:tools="" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_margin="25dp" tools:context=".MainActivity" > <TextView android:id=&…