android 来电去电监听
16lz
2021-01-26
package com.pocketdigi.phonelistener; import android.app.Service;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.telephony.PhoneStateListener;import android.telephony.TelephonyManager; public class PhoneReceiver extends BroadcastReceiver { @Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubSystem.out.println("action"+intent.getAction());if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){//如果是去电(拨出)System.out.println("拨出");}else{//查了下android文档,貌似没有专门用于接收来电的action,所以,非去电即来电System.out.println("来电");TelephonyManager tm = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE); tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);//设置一个监听器}}PhoneStateListener listener=new PhoneStateListener(){ @Overridepublic void onCallStateChanged(int state, String incomingNumber) {// TODO Auto-generated method stub//state 当前状态 incomingNumber,貌似没有去电的APIsuper.onCallStateChanged(state, incomingNumber);switch(state){case TelephonyManager.CALL_STATE_IDLE:System.out.println("挂断");break;case TelephonyManager.CALL_STATE_OFFHOOK:System.out.println("接听");break;case TelephonyManager.CALL_STATE_RINGING:System.out.println("响铃:来电号码"+incomingNumber);//输出来电号码break;}} };}
要在AndroidManifest.xml注册广播接收器:
123456 | <receiver android:name=".PhoneReceiver"> <intent-filter> <action android:name="android.intent.action.PHONE_STATE"/><action android:name="android.intent.action.NEW_OUTGOING_CALL" /> </intent-filter> </receiver> |
还要添加权限:
12 | <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"></uses-permission> |
更多相关文章
- Android(安卓)来电归属地显示功能demo
- Android监听手机电话状态与发送邮件通知来电号码的方法(基于Phon
- Android来电和短信操作
- Android(安卓)解决 HorizontalScrollView 里的内容滑动不全的问
- Android(安卓)Timer编写方式深解(貌似使用Thread不行,得使用Timer
- Android(安卓)6.0+ TelephonyManager 使用示例(3)来电静音和挂断
- Android(安卓)4.0 Phone拨号和来电流程分析
- Android来电拦截及拦截后的提示音
- android settings模块中添加来电反转静音功能