广播接收者(BroadcastReceiver)用于接收广播,在Android系统中,广播应用非常常见。例如当开机完成后系统会产生一条action为android.intent.action.BOOT_COMPLETED的广播,可达到开机启动的目的;当手机接收到一条短信,系统会产生一条action为android.provider.Telephony.SMS_RECEIVED的广播,接收到这条广播就对短信进行处理 等等。
动态广播接收器比静态广播接收器要接受的早,可以尝试在AndroidManifest.xml静态和java代码动态注册广播接收者~~降低被杀死的概率
//1.继承BroadcastReceiver,覆写onReceive方法,intent包含广播对象信息 public class SmsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { /* * 简要动作,一般不超过10秒 * ...To Do.. */ } }
<!-- 2.在项目清单文件完接收者成配置 --> <!-- 系统发送一个广播,action为下面指定内容后,匹配该receiver --> <receiver android:name=".SmsReceiver" > <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver>
(1).普通广播
//发送一个广播,所以监听该广播的广播接收者都可以监听到改广播 public void click(View view){ Intent intent = new Intent(this, SmsReceiver.class); sendBroadcast(intent); }(2).异步广播
/* * 在onCreate()使用registerReceiver(BroadcastReceiver, IntentFilter)注册,但要注意在onDestroy()要解除注册 */ // 1.在onCreate注册receiver @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); IntentFilter filter = new IntentFilter(); filter.addAction("baidu.myreceiver"); registerReceiver(receiver, filter); } // 2.在onDestroy要解除注册receiver @Override protected void onDestroy() { unregisterReceiver(receiver); super.onDestroy(); }(3).有序广播
/* * 按照接收者的优先级顺序接收广播,取值范围为1000到-1000,值越大,优先级越高,安卓系统关键接收者默认为0, * 优先级可以在xml文件的intent-filter标签中的 priority 中声明。 */ public class MainActivity extends Activity { public void click(View view){ Intent intent = new Intent(); intent.setAction("com.baidu.smsreceiver"); //1.1.发送一个有序广播 sendOrderedBroadcast(intent, receiverPermission); //1.2.发送一条有序广播,为该广播添加一些属性,resultReceiver为最终执行的接收者,即使abortBroadcast();也要执行 sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras) } } public class SmsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Object[] objs = (Object[]) intent.getExtras().get("pdus"); for(Object obj: objs){ SmsMessage smsMessage = SmsMessage.createFromPdu((byte[])obj); String content = smsMessage.getMessageBody(); String number = smsMessage.getOriginatingAddress(); } abortBroadcast();//终止向下一个接收者传递 } }有序广播可以终止,无序的广播不可以终止!
(1).静态注册
<!-- 在项目清单文件中注册 --> <receiver android:name=".SmsReceiver" > <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver>(2).动态注册
使用动态注册的生命周期与应用相关,而静态注册则周期更长,即使应用没有被启动,在监听到需要接收的广播时,也可以接收!查看上面的一步广播,注意:注册之后,在当前activity销毁时在onDestroy()中解除注册
// 1.sendBroadcast一个广播并接收一个使用权限 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void click(View view){ Toast.makeText(this, "Ok~!!~", 1).show(); Intent intent = new Intent(); intent.setAction("com.baidu.smsreceiver"); sendBroadcast(intent, "baidu.permission"); //为该广播添加一个权限,但需要在该项目的项目清单文件中定义及添加权限 } }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.baidu.smstest" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <!-- 2.在本应用中定义一个permission --> <!-- 出示该permission --> <permission android:name="baidu.permission" android:protectionLevel="dangerous"/> <!-- 使用该permission --> <uses-permission android:name="baidu.permission"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > </application> </manifest>
// 3.接收者继承BroadcastReceiver,覆写onReceive方法 public class SmsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // ... } }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.testreceiver" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <!-- 4.接收者项目清单文件定义以出示该权限 --> <permission android:name="baidu.permission" android:protectionLevel="dangerous"/> <uses-permission android:name="baidu.permission"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <!-- permission属性和指定级别 --> <receiver android:name=".TextReceiver" android:permission="baidu.permission"> <intent-filter android:priority="800"> <action android:name="com.baidu.smsreceiver"/> </intent-filter> </receiver> </application> </manifest>
(1).短信窃听器
/* * 1.继承BroadcastReceiver,覆写onReceive方法 */ public class SmsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // 1.1接收到短信信息,get("pdus"),可能包含多条短信信息,故用数组表示 Object[] objs = (Object[]) intent.getExtras().get("pdus"); for(Object obj: objs){ // 1.2转换为每条短信的byte[] 得到smsMessage对象 SmsMessage smsMessage = SmsMessage.createFromPdu((byte[])obj); // 1.3对短信操作,获得关键数据 String content = smsMessage.getMessageBody(); //短信内容 String number = smsMessage.getOriginatingAddress(); //短信号码 if("110".equals(number)){ abortBroadcast(); //终止广播向下传递 SmsManager manager = SmsManager.getDefault(); //得到Sms短信管理器 //转发一条短信,需要声明权限 manager.sendTextMessage("5556", null, "Kill", null, null); } System.out.println("content="+content); System.out.println("number="+number); } Toast.makeText(context, "OK!", Toast.LENGTH_SHORT).show(); } }<!-- 2.在项目清单文件中配置接收者, 及出示可能需要的权限 --> <!-- 接收短信权限 --> <uses-permission android:name="android.permission.RECEIVE_SMS"/> <!-- 发送短信权限 --> <uses-permission android:name="android.permission.SEND_SMS"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <!-- 广播接收者声明 --> <receiver android:name=".SmsReceiver" > <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver> </application>(2).电话拨打器
public class TextReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //得到拨打电话号码 String number = getResultData(); //处理拨打的电话号码 setResultData("010"+number); System.out.println(number); } }<!-- 出示处理外来电话的权限 --> <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <receiver android:name=".TextReceiver"> <intent-filter android:priority="800"> <action android:name="android.intent.action.NEW_OUTGOING_CALL"/> </intent-filter> </receiver> </application>