要实现监听到打电话和接电话的状态,需要用到广播接受者BroadcastReceiver,其实现代码请参考如下;
一、定义一个类,继承BroadcastReceiver,重写onReceive()方法。
1 package com.example.phonereceiver; 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 9 public class PhoneReceiver extends BroadcastReceiver {10 11 @Override12 public void onReceive(Context context, Intent intent) {13 if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) { //去电14 System.out.println("去电");15 } else { //来电(存在以下三种情况)16 TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);17 switch (tm.getCallState()) {18 case TelephonyManager.CALL_STATE_IDLE:19 System.out.println("挂断");20 break;21 case TelephonyManager.CALL_STATE_OFFHOOK:22 System.out.println("接听");23 break;24 case TelephonyManager.CALL_STATE_RINGING:25 System.out.println("响铃");26 break;27 }28 }29 }30 }
二、在清单文件中注册该广播,并加上相应的权限。
15 6 9 10 11 12 13 17 18 23 24 2519 2220 21