要监听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
本文转自欢醉博客园博客,原文链接http://www.cnblogs.com/zhangs1986/p/3243061.html如需转载请自行联系原作者
欢醉