要监听android打电话和接电话,只需下面2步骤
1.第一步,写一个Receiver继承自BroadcastReceiver1 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 @Override16 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 } else25 {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,
另外注意加上相应的权限12 73 64 5 8
Android监听来电和去电 | 若水工作室