BroadcastReceiver学习
一、使用系统广播。以监听电话状态为例
1、写一个类继承自BroadcastReceiver类
1 package com.diysoul.android.blacklist.receivers; 2 3 import android.app.Service; 4 import android.content.BroadcastReceiver; 5 import android.content.Context; 6 import android.content.Intent; 7 import android.telephony.TelephonyManager; 8 import android.util.Log; 9 10 public class IncomingcallReceiver extends BroadcastReceiver { 11 12 private static final String TAG = "IncomingcallReceiver"; 13 14 private boolean incomingFlag = false; 15 private String incoming_number = null; 16 17 @Override 18 public void onReceive(Context context, Intent intent) { 19 Log.v(TAG, "onReceive,Action:" + intent.getAction()); 20 21 // 如果是拨打电话 22 if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) { 23 incomingFlag = false; 24 String phoneNumber = intent 25 .getStringExtra(Intent.EXTRA_PHONE_NUMBER); 26 Log.i(TAG, "call OUT:" + phoneNumber); 27 } else { 28 // 如果是来电 29 TelephonyManager tm = (TelephonyManager) context 30 .getSystemService(Service.TELEPHONY_SERVICE); 31 32 switch (tm.getCallState()) { 33 case TelephonyManager.CALL_STATE_RINGING: 34 incomingFlag = true;// 标识当前是来电 35 incoming_number = intent.getStringExtra("incoming_number"); 36 Log.i(TAG, "RINGING :" + incoming_number); 37 break; 38 case TelephonyManager.CALL_STATE_OFFHOOK: 39 if (incomingFlag) { 40 Log.i(TAG, "incoming ACCEPT :" + incoming_number); 41 } 42 break; 43 44 case TelephonyManager.CALL_STATE_IDLE: 45 if (incomingFlag) { 46 Log.i(TAG, "incoming IDLE"); 47 } 48 break; 49 } 50 } 51 } 52 }
2、配置AndroidManifest.xml
1 <receiver android:name="com.diysoul.android.blacklist.receivers.IncomingcallReceiver"> 2 <intent-filter> 3 <action android:name="android.intent.action.PHONE_STATE" /> 4 </intent-filter> 5 </receiver>
3、配置系统权限
1 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
二、自定义广播事件
1.发送广播
1 Intent intent = new Intent(); 2 //自定义一个广播动作。 3 intent.setAction(action); 4 //发送无序广播,所有接收都都可以收到,不可拦截或修改 5 sendBroadcast(intent); 6 //发送有序广播,可以被拦截或修改,也可以被终止 7 sendOrderedBroadcast(intent, receiverPermission); 8 sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras);
2.接收广播放的类,修改或终止广播,只针对有序广播。对于无序广播,会报异常,将不会执行相应的功能。
1 //修改广播数据 2 setResultData(data); 3 setResultExtras(extras); 4 //终止继续发送广播,低优先级或同优先级但后部署的应用将不能收到 5 //有一种例外是resultReceiver指定的对象仍可收到消息,但前面的应用若修改后,即使收到也是修改后的数据 6 abortBroadcast();
3.接收广播放的类,配置AndroidManifest.xml
1 //设置优先级priority的值 -1000 ~ 1000 数值级别相同,则先安装的应用先收到。同一个应用中,先声明的receiver先收到 2 <receiver android:name="CLASSNAME" > 3 <intent-filter android:priority="100" > 4 <action android:name="ACTION" /> 5 </intent-filter>
代码养活自己