天天看点

Android 四大组件之一:BroadcastReceiver广播机制

一、BroadcastReceiver介绍

  BroadcastReceiver是Android的四大组件之一,与Activity和Service具有完整声明周期不同。它本质上是一种全局监听器,用于监听系统全局的广播消息。因此它可以方便地实现系统中不同组件之间的通信。

二、BroadcastReceiver的使用

  BroadcastReceiver用于接收程序所发出的 Broadcast Intent事件,它的启动使用步骤:

1、创建class继承BroadcastReceiver。

2、注册广播(静态注册于动态注册)。

2、创建Intent(这里Intent的启动可以是隐式启动也可以是显示启动)。

3、new BroadcastReceiver()对象调用sendBroadcast(intent)方法。

三、简单实例使用:

1、创建MyReceiver 类 继承BroadcastReceiver(重写onReceive方法)

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
    //  Toast.makeText(context, "我接收到了广播",Toast.LENGTH_LONG ).show();
        Log.d("广播", "我接收到了广播");
    }

}      

注意:

1、如果系统找不到Activity的组件可能会报异常,程序终止,但是BroadcastReceiver如果找不到合适的组件应用不会有任何异常。

2、onReceive方法不中不能有耗时操作,如果onReceive方法在10秒内不能执行完成则认为该进程无响应。

2、静态注册与动态注册

♬(1)静态注册(​

​<receiver android:name="com.example.mybroadcast.MyReceiver" > </receiver>​

​​)

下面添加在manifest中的注册(包含了一个隐式启动)

<receiver android:name="com.example.mybroadcast.MyReceiver"
            <intent-filter>
                <action android:name="hahaha"
            </intent-filter>
        </receiver>      

♬(2)动态注册(​

​registerReceiver(mreceiver, filter);​

​​)

  在Activity中进行动态注册广播的时候需要覆写onDestroy方法用于注销。

//代码中注册广播相当于manifest中的注册
        mreceiver=new MyReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction("hahaha");
        registerReceiver(mreceiver, filter);      
@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    unregisterReceiver(mreceiver);
}      

4、MainActivity中设置(创建类、创建Intent、发送广播)

@Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.bt_send:
            Intent intent=new Intent();
            intent.setAction("hahaha");
            sendBroadcast(intent);

        //  Toast.makeText(getApplicationContext(), "发送广播",Toast.LENGTH_LONG ).show();
            break;

        default:
            break;
        }

    }      

四、闹钟广播

Android 四大组件之一:BroadcastReceiver广播机制
mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);      
private void cancelalarm() {
        Intent intent = new Intent();
        intent.setAction("hahaha");
        PendingIntent pending = PendingIntent.getBroadcast(
                getApplicationContext(), 0x22, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mAlarmManager.cancel(pending);

    }

    private void wakeupalarm() {
        Intent intent = new Intent();
        intent.setAction("hahaha");
        PendingIntent pending = PendingIntent.getBroadcast(
                getApplicationContext(), 0x22, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis() + 5000, 5000, pending);
    }      

五、接收系统广播消息

1、​​Android 系统广播大全​​

2、实例:监听app卸载与wifi状态

添加

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
   <uses-permission android:name="android.permission.broadcast_packaged_removed"/>      
<receiver android:name=".MyReceiver">
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_CHANGED"
                <action android:name="android.net.wifi.STATE_CHANGE"/>              
            </intent-filter>
        </receiver>      

完整

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17"
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
   <uses-permission android:name="android.permission.broadcast_packaged_removed"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        <activity
            android:name="com.example.mybroadcast.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="android.intent.action.PACKAGE_CHANGED"
                <action android:name="android.net.wifi.STATE_CHANGE"/>              
            </intent-filter>
        </receiver>

    </application>

</manifest>