Android应用开发学习笔记之BroadcastReceiver

作者:刘昊昱 

博客:http://blog.csdn.net/liuhaoyutz

 

一、BroadcastReceiver机制概述

 

Broadcast Receiver是Android的一种“广播发布/消息接收”机制,或者说的更准确一些,是一种“监听”机制。作为广播发布者的应用程序,可以在不知道谁(如果有的话)将接收这个广播消息的情况下发出一个广播消息(广播的消息实际上就是一个Intent对象)。而消息接收者可以指定自己将接收哪些消息(通过使用intent-filter),如果出现了他指定的消息,消息接收者就会被调用对消息进行处理。

要发出一个广播消息,可以创建一个Intent对象,并调用sendBroadcast()方法将Intent对象做为消息广播出去。

广播消息的接收是通过继承BroadcastReceiver类来实现的,我们需要实现onReceive()函数,在该函数中完成对消息(即Intent对象)的处理。

 

二、自定义广播消息

 

下面来看一个例子程序,该程序演示怎样自定义一个广播消息并发送出去,同时也演示了怎样接收指定消息并处理,该程序运行效果如下:

Android应用开发学习笔记之BroadcastReceiver

先来看主布局文件,其内容如下:

 

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >

 

   <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:textSize="20dp"

        android:text="@string/hello" />

   

   <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/button"

        android:onClick="onButtonClick"

        android:textSize="20dp"

        android:text="发送消息" />

 

</LinearLayout>


 

下面来看主Activity文件,其内容如下:

 

package com.liuhaoyu;

 

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

 

public class MainActivity extendsActivity {

         privatestatic final String MY_ACTION="com.liuhaoyu.broastcast.action.MY_ACTION";

        

   /** Called when the activity is first created. */

   @Override

   public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

   }

   

   public void onButtonClick(View v) {

            Intent intent=newIntent();

            intent.setAction(MY_ACTION);

            intent.putExtra("msg","Broadcast Receiver测试");

            sendBroadcast(intent);

   }

}


 

当点击按钮时,创建一个广播消息(即Intent对象),指定该消息对应的Action是MY_ACTION,通过调用sendBroadcast()函数将消息广播出去。

下面来看该程序自定义的BraodcastReceiver:

 

package com.liuhaoyu;

 

importandroid.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.widget.Toast;

 

public class BroadcastReceiverTestextends BroadcastReceiver {

 

         @Override

         publicvoid onReceive(Context arg0, Intent arg1) {

                   //TODO Auto-generated method stub

                   Stringmsg=arg1.getStringExtra("msg");

                   Toast.makeText(arg0,msg, Toast.LENGTH_LONG).show();

         }

        

}


 

可以看到,我们继承了BroadcastReceiver类,并实现了onReceiver()函数,该函数中对消息的处理就是弹出一个消息提示。

下面程序在AndroidManifest.xml文件中声明BroadcastReceiverTest,并通过intent-filter指定监听MY_ACTION消息:

 

        <receiver android:name=".BroadcastReceiverTest">

            <intent-filter>

                <action android:name="com.liuhaoyu.broastcast.action.MY_ACTION"/>

            </intent-filter>

        </receiver>


 

 

三、接收系统预定义广播消息

 

Android系统提供了一些预定义的广播消息,Android官方文档上关于消息(即Intent对象)对应的Action描述如下:

These are the currentstandard actions that Intent defines for receiving broadcasts (usually through registerReceiver(BroadcastReceiver,IntentFilter) ora <receiver> tag in a manifest).

·        ACTION_TIME_TICK

·        ACTION_TIME_CHANGED

·        ACTION_TIMEZONE_CHANGED

·        ACTION_BOOT_COMPLETED

·        ACTION_PACKAGE_ADDED

·        ACTION_PACKAGE_CHANGED

·        ACTION_PACKAGE_REMOVED

·        ACTION_PACKAGE_RESTARTED

·        ACTION_PACKAGE_DATA_CLEARED

·        ACTION_UID_REMOVED

·        ACTION_BATTERY_CHANGED

·        ACTION_POWER_CONNECTED

·        ACTION_POWER_DISCONNECTED

·        ACTION_SHUTDOWN

下面看一个接收系统预定义的BOOT_COMPLETE广播消息的例子,当Android启动起来后,会广播BOOT_COMPLETE消息,我们的应用程序声明监听该消息,所以每次Android启动起来后,我们的应用程序就会做出对该消息的响应,怎样响应就是我们在onReceiver()函数中实现的,这个程序的响应是播放一段音乐,弹出一个提示信息,并打印LOG信息。该程序运行效果如下:

Android应用开发学习笔记之BroadcastReceiver

下面是LogCat中显示的LOG信息:

我们先来看主布局文件:

 

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >

 

   <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/hello" />

 

</LinearLayout>


 

没有什么特殊的,就是系统自动生成的,我们不做任何改变。

下面看主Activity文件,其内容如下:

 

package com.liuhaoyu;

 

import android.app.Activity;

import android.os.Bundle;

 

public class MainActivity extendsActivity {    

   /** Called when the activity is first created. */

   @Override

   public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

   }

}


 

也是系统自动生成的,不做任何改变。

下面就是重点了,即我们的BroadcastReceiver的实现:

 

package com.liuhaoyu;

 

importandroid.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.media.MediaPlayer;

import android.util.Log;

import android.widget.Toast;

 

public class BootReceiver extendsBroadcastReceiver {

         @Override

         publicvoid onReceive(Context context, Intent intent) {

                   Log.e("BootReceiver","received BOOT_COMPLETED intent!");           

                   MediaPlayer.create(context,R.raw.enter).start();                 

                   Toast.makeText(context,"BroadcastReceiver: " + intent.getAction(),Toast.LENGTH_SHORT).show();

         }

}


 

可以看到,我们继承了BraodcastReceiver类,实现了onReceiver()函数,在该函数中,打印一条LOG信息,播放一段音乐,并弹出一个提示信息,这就是我们的应用程序接收到指定广播消息后的处理。

有了BroadcastReceiver,还有一个重要的任务是声明我们的应用程序监听哪些消息,这个工作是在AndroidManifest.xml文件中完成的,在系统默认内容之外,添加了两处内容:

一是声明BroadcastReceiver,同时通过intent-filter指定监听BOOT_COMPLETED消息:

 

        <receiver android:name=".BootReceiver">

        <intent-filter>

                <action android:name="android.intent.action.BOOT_COMPLETED">   

                </action>

            </intent-filter>

        </receiver>   


 

二是指定权限:

 

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>


 

 

你可能感兴趣的:(Android应用开发学习笔记之BroadcastReceiver)