静态注册广播也称常驻广播,动态注册广播在取消注册后便不再监听广播事件,而静态广播即使没有启动应用也可以监听广播事件。创建步骤主要分为创建一个广播接收器的子类,以及在配置清单文件中静态注册广播
案例
A.发送方,见我的另一篇blog动态广播,发送方代码相同
B.接收方
1.写一个类 继承BroadcastReceiver
package com.example.broadcasetsendstatic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
//静态广播要在清单文件中配置,然后写一个类继承BroadcastReceiver
//即使应用退出了,静态广播(常驻广播)依然可以接收到广播信息
//静态广播比较消耗资源
public class StaticBroadcast extends BroadcastReceiver {
private static final String broadcast = "com.chj";
private static final String TAG = "chj";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(action.equals(broadcast)){
Log.e(TAG, "ok-----------------");
}
}
}
2.在清单文件配置广播接受者
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcasetsendstatic"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.broadcasetsendstatic.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=".StaticBroadcast">
<intent-filter >
<action android:name="com.chj"/>
</intent-filter>
</receiver>
</application>
</manifest>