Android之BroadcastReceiver

Android广播机制包含三个基本要素:
广播发送者(调用sendBroadcast方法) - 用于发送广播;
广播接收器(BroadcastReceiver) - 用于接收广播;
意图内容(Intent)-用于保存广播相关信息的媒介。
Broadcast是Android中一种广泛运用的在应用程序之间或应用程序内个组件直接传输信息的机制。而BroadcastReceiver是对发送出来的广播Intent进行过滤接受并响应的一类组件。

BroadcastReceiver广播接收者用于异步接收广播Intent,广播Intent的发送是通过调用Context.sendBroadcast()来实现的。通常一个广播Intent可以被订阅了此Intent的多个广播接收者所接收。

每次广播Intent发出后,系统就会创建对应的BroadcastReceiver的实例,并自动触发它的onReceiver()方法,onReceiver()方法执行完后,BroadcastReveiver的实例就会被销毁。

通常一个BroadcastReceiver对象的生命周期不超过5秒,所以在BroadcastReceiver里不能做一些比较耗时的操作。如果需要根据Broadcast来完成一项比较耗时的操作,则可以考虑通过Intent启动一个Service来完成该操作。

实例:BroadcastDemo
运行效果:

代码清单:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.rainsong.broadcastdemo"
      android:versionCode="1"
      android:versionName="1.0">

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />

    <application android:label="@string/app_name" android:icon="@drawable/ic_launcher">
        <activity android:name="MainActivity"
                  android:label="@string/app_name">
            <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="com.rainsong.action.NEW_BROADCAST" /> 
            </intent-filter>
        </receiver>
    </application>
</manifest>
布局文件:main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:text="发送广播" 
    />
</LinearLayout>
Java源代码文件:MainActivity.java
package com.rainsong.broadcastdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity
{
    public final String ACTION = "com.rainsong.action.NEW_BROADCAST";

    Button btn1;

    OnClickListener listener1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn1 = (Button)findViewById(R.id.button1);
        listener1 = new OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(ACTION);
                sendBroadcast(intent);
            }
        };
        btn1.setOnClickListener(listener1);
    }
}
Java源代码文件:MyReceiver.java
package com.rainsong.broadcastdemo;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;


public class MyReceiver extends BroadcastReceiver {
    public static int NOTIFICATION_ID = 12345;

    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationManager nm = 
            (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(android.R.drawable.stat_notify_chat, 
            "MyReceiver onReceive", System.currentTimeMillis());
        Intent intent1 = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent1, 0);
        notification.setLatestEventInfo(context, "MyReceiver onReceive", null, pendingIntent);
        nm.notify(NOTIFICATION_ID, notification);  
    }
}

代码逻辑:
单击“发送广播”按钮,我们的程序开始发送广播Intent,这个广播Intent被MyReceiver所截获,然后就开始执行MyReceiver里的onReceive方法,在onReceive里边将一个Notification显示在状态栏中。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。