写个实例实现Android中来电和去电的监听,来电可以使用PhoneStateListener对电话状态的改变进行监听,去电需要动态或者静态去注册广播接收器,对去电进行监听;
来电:
来电所对应的三种静态成员常量:
1、CALL_STATE_IDLE:空闲状态,没有任何活动。
2、CALL_STATE_OFFHOOK:摘机状态,至少有个电话活动。该活动或是拨打(dialing)或是通话,或是 on hold。
3、CALL_STATE_RINGING:来电状态,电话铃声响起的那段时间或正在通话又来新电,新来电话不得不等待的那段时间。
去电:
通过自定义广播接收器,监听手机发出的android.intent.action.NEW_OUTGOING_CALL的广播,然后在广播接收器中处理去电的相关逻辑。
实例代码实现:
public class PhoneListenService extends Service {
private static final String tag = "PhoneListenService";
private TelephonyManager mTelephonyManager;
private MyPhoneStateListener myPhoneStateListener;
private InnerOutCallReceiver mInnerOutCallReceiver;
@Override
public void onCreate() {
mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
myPhoneStateListener = new MyPhoneStateListener();
mTelephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
mInnerOutCallReceiver = new InnerOutCallReceiver();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
registerReceiver(mInnerOutCallReceiver, intentFilter);
super.onCreate();
}
/**
* 动态注册广播接收器监听去电信息
*/
class InnerOutCallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String outPhone = getResultData();
Log.i(tag, "outPhone:" + outPhone);
}
}
/**
* 自定义内部类对来电的电话状态进行监听
*/
class MyPhoneStateListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
Log.i(tag, "响铃:" + incomingNumber);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.i(tag, "接听");
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.i(tag, "挂断");
break;
}
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
if (mTelephonyManager != null && myPhoneStateListener != null) {
mTelephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_NONE);
}
if (mInnerOutCallReceiver != null) {
unregisterReceiver(mInnerOutCallReceiver);
}
super.onDestroy();
}
}
权限添加:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
另外: 这里给大家提供一个AndroidManifest.xml中权限控制的在线查询工具:
Android Manifest功能与权限描述大全
测试结果如下: