Android监听来电和去电
要监听android打电话和接电话,只需下面2步骤
1.第一步,写一个Receiver继承自BroadcastReceiver
1 import android.app.Service; 2 import android.content.BroadcastReceiver; 3 import android.content.Context; 4 import android.content.Intent; 5 import android.telephony.TelephonyManager; 6 import android.util.Log; 7 8 public class PhoneStateBroadCastReceiver extends BroadcastReceiver 9 { 10 private static final String TAG = "PhoneStateBroadCastReceiver"; 11 12 private static boolean mIncomingFlag = false; 13 private static String mIncomingNumber = null; 14 15 @Override 16 public void onReceive(Context context, Intent intent) 17 { 18 // 如果是拨打电话 19 if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) 20 { 21 mIncomingFlag = false; 22 String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); 23 Log.i(TAG, "call OUT:" + phoneNumber); 24 } else 25 { 26 // 如果是来电 27 TelephonyManager tManager = 28 (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE); 29 switch (tManager.getCallState()) 30 { 31 case TelephonyManager.CALL_STATE_RINGING: 32 mIncomingNumber = intent.getStringExtra("incoming_number"); 33 Log.i(TAG, "RINGING :" + mIncomingNumber); 34 break; 35 case TelephonyManager.CALL_STATE_OFFHOOK: 36 if (mIncomingFlag) 37 { 38 Log.i(TAG, "incoming ACCEPT :" + mIncomingNumber); 39 } 40 break; 41 case TelephonyManager.CALL_STATE_IDLE: 42 if (mIncomingFlag) 43 { 44 Log.i(TAG, "incoming IDLE"); 45 } 46 break; 47 } 48 } 49 } 50 51 }
第二步:在AndroidManifest.xml,配置写好的Receiver,并拦截相应的BroadCastAction,
另外注意加上相应的权限
1 <receiver android:name=".broadcase.PhoneStateBroadCastReceiver"> 2 <intent-filter> 3 <action android:name="android.intent.action.PHONE_STATE"/> 4 <action android:name="android.intent.action.NEW_OUTGOING_CALL" /> 5 </intent-filter> 6 </receiver> 7 <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 8 <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
Android监听来电和去电 | 若水工作室 http://www.92coding.com/blog/index.php/archives/46.html
作者:欢醉
公众号【一个码农的日常】 技术群:319931204 1号群: 437802986 2号群: 340250479
出处:http://zhangs1986.cnblogs.com/
码云:https://gitee.com/huanzui
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
公众号【一个码农的日常】 技术群:319931204 1号群: 437802986 2号群: 340250479
出处:http://zhangs1986.cnblogs.com/
码云:https://gitee.com/huanzui
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。