Latest web development tutorials

Android broadcast receiver (Broadcast Receivers)

Broadcast receiver in response to the broadcast message to other applications or systems. These messages are sometimes called events or intentions. For example, an application can initiate a broadcast to allow other applications to guide some of the data has been downloaded to the device, and they can be used. Such broadcast receiver may define appropriate action to intercept these communications.

There are two important steps to make the intent of broadcasting system with a broadcast receiver to work.

  • Create broadcast receiver
  • Registered broadcast receiver

There is an additional step to achieve the intent of the custom, you must create and broadcast these intentions.


Create broadcast receiver

Broadcast receiver needs to be implemented as a subclass BroadcastReceiver class and override onReceive () method receives the Intent object as a parameter of the message.

public class MyReceiver extends BroadcastReceiver {
   @Override
   public void onReceive(Context context, Intent intent) {
      Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
   }
}

Registered broadcast receiver

By application registered in AndroidManifest.xml broadcast receiver to receive broadcast intent to develop. Suppose we want to register MyReceiver to monitor system-generated ACTION_BOOT_COMPLETED event. This event is issued when the process started by the Android system is complete.

Broadcast receiver (Broadcast Receivers)

<application
   android:icon="@drawable/ic_launcher"
   android:label="@string/app_name"
   android:theme="@style/AppTheme" >
   <receiver android:name="MyReceiver">

      <intent-filter>
         <action android:name="android.intent.action.BOOT_COMPLETED">
         </action>
      </intent-filter>

   </receiver>
</application>

Now, whenever Android device is activated, the interceptors will be broadcast receiver MyReceiver, and onReceive () implemented logic will be executed.

There are many events generated by the system is defined as a class Intent static constant value. The following table lists the important system events.

Event Constants description
android.intent.action.BATTERY_CHANGED Durable broadcasting, including battery state of charge, the level and other information.
android.intent.action.BATTERY_LOW Low battery condition identification device.
android.intent.action.BATTERY_OKAY Identifies the battery power is low, it is now has been good.
android.intent.action.BOOT_COMPLETED After the system has finished booting broadcast again.
android.intent.action.BUG_REPORT Display Report bug activity.
android.intent.action.CALL Call someone to perform the specified data.
android.intent.action.CALL_BUTTON Users click on the "Call" button to open the dialer or other suitable interface dial.
android.intent.action.DATE_CHANGED Date changes.
android.intent.action.REBOOT Device restart.

Custom broadcast intent

If you want your application to generate and send a custom intent, you need to create and transmit these intentions in class activities through sendBroadcast (). If you use sendStickyBroadcast (Intent) method is intended to be permanent (sticky), which means that your intent issued after the completion of the broadcast has been maintained.

public void broadcastIntent(View view)
{
   Intent intent = new Intent();
   intent.setAction("cn.uprogrammer.CUSTOM_INTENT");
   sendBroadcast(intent);
}

cn.uprogrammer.CUSTOM_INTENT intentions as intentions before we can produce the same registration system is registered.

<application
   android:icon="@drawable/ic_launcher"
   android:label="@string/app_name"
   android:theme="@style/AppTheme" >
   <receiver android:name="MyReceiver">

      <intent-filter>
         <action android:name="cn.uprogrammer.CUSTOM_INTENT">
         </action>
      </intent-filter>

   </receiver>
</application>

Examples

This example will explain how to create a broadcast receiver to intercept a custom intent. Once you're familiar with custom intent, you can program the application to intercept intent generated by the system. Let us follow the following steps to modify Android application Hello World Examples section we created.

step description
1 Use Android Studio to create an Android application and name broadcastreceiver, and placed under the Hello World examples chapter cn.uprogrammer.broadcastreceiver package.
2 The main activities to modify the file MainActivity.java add broadcastIntent () method.
3 Create a new Java file named MyReceiver.java at cn.uprogrammer.broadcastreceiver package to define the broadcast receiver.
4 An application can process one or more custom or intention of the system, without any restrictions. Each intention you want to ban need to use <receiver ... /> tag registered in AndroidManifest.xml.
5 Modify res / layout / activity_main.xml file contains a default content to broadcast intent button.
6 You do not need to modify the string file, Android Studio will pay attention string.xml file.
7 Launch Android emulator to run the application and verify the results of changes made to the application.

Here is the content of the modified main activity file src / cn.uprogrammer.broadcastreceiver / MainActivity.java of. This file contains each of the basic life-cycle approach. We've added broadcastIntent () method to broadcast custom events.

package cn.uprogrammer.broadcastreceiver;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.view.View;

public class MainActivity extends Activity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    // 广播自定义意图
    public void broadcastIntent(View view){
        Intent intent = new Intent();
        intent.setAction("cn.programmer.CUSTOM_INTENT");
        sendBroadcast(intent);
    }
}

Here's what src / cn.uprogrammer.broadcastreceiver / MyReceiver.java of:

package cn.uprogrammer.broadcastreceiver;

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

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "检测到意图。", Toast.LENGTH_LONG).show();
    }
}

Then modify AndroidManifest.xml file. Here by adding <receiver ... /> tag to include our broadcast receiver:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.uprogrammer.broadcastreceiver"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="22" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>

        </activity>

        <receiver android:name="MyReceiver">

            <intent-filter>
                <action android:name="cn.programmer.CUSTOM_INTENT">
                </action>
            </intent-filter>

        </receiver>

    </application>

</manifest>

Here is the content of res / layout / activity_main.xml file, including broadcast intent custom buttons.

<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="广播实例"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="30dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="www.uprogrammer.cn"
        android:textColor="#ff87ff09"
        android:textSize="30dp"
        android:layout_above="@+id/imageButton"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="40dp" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButton"
        android:src="@drawable/ic_launcher"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:text="广播意图"
        android:onClick="broadcastIntent"
        android:layout_below="@+id/imageButton"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Here is the content of res / values ​​/ strings.xml file defines two new constants.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Android Broadcast Receiver</string>
    <string name="action_settings">Settings</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Main Activity</string>

</resources>

Let's just run a modified Hello World! Application. I assume you've created AVD during the installation environment. Open your project in the active file, click on the toolbar image Icon to run the application In Android Studio. Android Studio install the application on the AVD and starts it. If all goes well, it will be displayed on the emulator window as follows:

image

Now click on "Broadcast intent" button to broadcast our custom intentions. It will broadcast our custom intent "cn.programmer.CUSTOM_INTENT", intercepting and executing our logic implemented in our broadcast receiver MyReceiver registered in. The toast will appear at the bottom of the simulator. as follows:

image

You can try to implement other broadcast receiver to intercept intent generated by the system, such as system startup, date changes and low power usage.