Android 来电监听

2024-06-01 15:32
文章标签 android 监听 来电

本文主要是介绍Android 来电监听,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近刚接到一个需求,为BOSS做一个来电显示功能,查找号码库显示姓名角色。

一、查找来电监听方法

PhoneStateListener监听器类,用于监视设备上特定电话状态的变化,包括服务状态、信号强度、消息等待指示器(语音邮件)等。

import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;public class MyPhoneStateListener extends PhoneStateListener {private static final String TAG = "MyPhoneStateListener";protected CallListener listener;/*** 返回电话状态** CALL_STATE_IDLE 无任何状态时* CALL_STATE_OFFHOOK 接起电话时* CALL_STATE_RINGING 电话响铃时*/@Overridepublic void onCallStateChanged(int state, String incomingNumber) {switch (state) {case TelephonyManager.CALL_STATE_IDLE:Log.d(TAG ,"电话挂断...");listener.onCallIdle();break;case TelephonyManager.CALL_STATE_OFFHOOK:Log.d(TAG ,"正在通话...");listener.onCallOffHook();break;case TelephonyManager.CALL_STATE_RINGING:Log.d(TAG ,"电话响铃...");listener.onCallRinging();break;}super.onCallStateChanged(state, incomingNumber);}//回调public void setCallListener(CallListener callListener) {this.listener = callListener;}//回调接口public interface CallListener {void onCallIdle();void onCallOffHook();void onCallRinging();}
}

TelephonyManager 提供对设备上电话服务的信息的访问。应用程序可以使用该类中的方法来确定电话服务和状态,以及访问某些类型的订阅者信息。应用程序还可以注册侦听器来接收电话状态更改的通知。

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import com.flymbp.callmonitor.MyPhoneStateListener;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);telephony();}private void telephony() {//获得相应的系统服务TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);if(tm != null) {try {MyPhoneStateListener myPhoneStateListener = new MyPhoneStateListener();myPhoneStateListener.setCallListener(new MyPhoneStateListener.CallListener() {@Overridepublic void onCallIdle() {}@Overridepublic void onCallOffHook() {}@Overridepublic void onCallRinging() {//走接口查询号码信息}});// 注册来电监听tm.listen(myPhoneStateListener, MyPhoneStateListener.LISTEN_CALL_STATE);} catch(Exception e) {// 异常捕捉}}}
}

此时此刻我们就可以监听到来电状态,但是incomingNumber没值,测试设备是华为mate20 pro Android 9.0
需要READ_CALL_LOG权限

  	<!--读取电话的状态信息的权限--><uses-permission android:name="android.permission.READ_PHONE_STATE" /><!--读取通话记录的权限--><uses-permission android:name="android.permission.READ_CALL_LOG" />

Android 9 来电监听incomingNumber为空

拿到incomingNumber 我们就可以请求后台接口来获取号码信息,或者有本地号码数据库进行查找。

二、来电弹窗提示信息

来电号码信息有了,我们要在来电界面进行提示,既然不能对来电界面进行篡改,那我们就加个弹窗提示吧。
想到两种方式:
1、Toast提示,实现简单,但是显示时间短,不是主动触发,会错过看到提示,不采用。
2、悬浮窗提示,既然要在自身应用以外的界面上显示弹窗,那必然要使用悬浮窗。

我们将使用悬浮窗进行来电提示。为了让悬浮窗与Activity脱离,使其在应用处于后台时悬浮窗仍然可以正常运行,这里使用Service来启动悬浮窗。

来电时显示悬浮窗,点击悬浮窗可移除,拖拽悬浮窗可移动,接通或挂断移除悬浮窗,注意悬浮窗不要来一个电话显示一个弹窗。

public class FloatingButtonService extends Service {public static boolean isStarted = false;private WindowManager windowManager;private WindowManager.LayoutParams layoutParams;private Button button;private String content;@Overridepublic void onCreate() {super.onCreate();isStarted = true;windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);layoutParams = new WindowManager.LayoutParams();if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;} else {layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;}layoutParams.format = PixelFormat.RGBA_8888;layoutParams.gravity = Gravity.LEFT | Gravity.TOP;layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;layoutParams.width = 500;layoutParams.height = 100;layoutParams.x = 300;layoutParams.y = 300;}@Nullable@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {content = intent.getStringExtra("content");int state = intent.getIntExtra("state", 0);switch (state) {case TelephonyManager.CALL_STATE_IDLE:removeFloating();break;case TelephonyManager.CALL_STATE_OFFHOOK:removeFloating();break;case TelephonyManager.CALL_STATE_RINGING:showFloatingWindow();break;}return super.onStartCommand(intent, flags, startId);}private void removeFloating() {if(button != null){windowManager.removeView(button);}}private void showFloatingWindow() {if(button != null){windowManager.removeView(button);}if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {if (Settings.canDrawOverlays(this)) {button = new Button(getApplicationContext());button.setText(content);button.setTextColor(Color.BLACK);button.setBackgroundColor(Color.WHITE);button.setOnTouchListener(new FloatingOnTouchListener());windowManager.addView(button, layoutParams);}} else {button = new Button(getApplicationContext());button.setText(content);button.setTextColor(Color.BLACK);button.setBackgroundColor(Color.WHITE);button.setOnTouchListener(new FloatingOnTouchListener());windowManager.addView(button, layoutParams);}}private class FloatingOnTouchListener implements View.OnTouchListener {private int x;private int y;private int clickx;private int clicky;@Overridepublic boolean onTouch(View view, MotionEvent event) {switch (event.getAction()) {case MotionEvent.ACTION_DOWN:x = (int) event.getRawX();y = (int) event.getRawY();clickx = x;clicky = y;break;case MotionEvent.ACTION_MOVE:int nowX = (int) event.getRawX();int nowY = (int) event.getRawY();int movedX = nowX - x;int movedY = nowY - y;x = nowX;y = nowY;layoutParams.x = layoutParams.x + movedX;layoutParams.y = layoutParams.y + movedY;windowManager.updateViewLayout(view, layoutParams);break;case MotionEvent.ACTION_UP:if (clickx == x && clicky == y)windowManager.removeView(button);break;default:break;}return false;}}
}

如何触发悬浮窗呢?

BroadcastReceiver使用广播来接收来电状态

在MainActivity.onCreate中注册广播

@Override
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);BroadcastReceiver mReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String data = intent.getStringExtra("data");showFloating(data);}};IntentFilter intentFilter = new IntentFilter("android.intent.action.MAIN");registerReceiver(mReceiver, intentFilter);
}public void showFloating(String mobile, int state) {Intent regIntent = new Intent(MainActivity.this, FloatingButtonService.class);regIntent.putExtra("content", mobile);regIntent.putExtra("state",state);startService(regIntent);
}

三、后台监听

来电监听我们不能总让应用在前台运行吧,这时需要后台运行进行监听。
需要把在MainActivity.telephony的方法写到服务里。

public class MyPhoneStateListenService extends Service {private static final String tag = "MyPhoneStateListenService";public static final String ACTION_REGISTER_LISTENER = "action_register_listener";// 电话管理者对象private TelephonyManager mTelephonyManager;// 电话状态监听者private MyPhoneStateListener myPhoneStateListener;@Overridepublic void onCreate() {mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);myPhoneStateListener = new MyPhoneStateListener(this);mTelephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);super.onCreate();}@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onDestroy() {// 取消来电的电话状态监听服务if (mTelephonyManager != null && myPhoneStateListener != null) {mTelephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_NONE);}super.onDestroy();}
}

在MainActivity.onCreate中开启服务

private void registerPhoneStateListener() {Intent intent = new Intent(this,  MyPhoneStateListenService.class);intent.setAction(MyPhoneStateListenService.ACTION_REGISTER_LISTENER);startService(intent);
}

四、进程保活

那么问题又来了,在后台服务很容易被杀,那我们就得考虑加入保活方案。
保活方案有很多,采用合适的方案,这里就不细说了。
常见的一些保活方案:
1、一像素保活
2、双进程守护
3、后台播放无声音乐
。。。

这篇关于Android 来电监听的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1021391

相关文章

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

C#监听txt文档获取新数据方式

《C#监听txt文档获取新数据方式》文章介绍通过监听txt文件获取最新数据,并实现开机自启动、禁用窗口关闭按钮、阻止Ctrl+C中断及防止程序退出等功能,代码整合于主函数中,供参考学习... 目录前言一、监听txt文档增加数据二、其他功能1. 设置开机自启动2. 禁止控制台窗口关闭按钮3. 阻止Ctrl +

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

Android DataBinding 与 MVVM使用详解

《AndroidDataBinding与MVVM使用详解》本文介绍AndroidDataBinding库,其通过绑定UI组件与数据源实现自动更新,支持双向绑定和逻辑运算,减少模板代码,结合MV... 目录一、DataBinding 核心概念二、配置与基础使用1. 启用 DataBinding 2. 基础布局

Android ViewBinding使用流程

《AndroidViewBinding使用流程》AndroidViewBinding是Jetpack组件,替代findViewById,提供类型安全、空安全和编译时检查,代码简洁且性能优化,相比Da... 目录一、核心概念二、ViewBinding优点三、使用流程1. 启用 ViewBinding (模块级

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

Kotlin Compose Button 实现长按监听并实现动画效果(完整代码)

《KotlinComposeButton实现长按监听并实现动画效果(完整代码)》想要实现长按按钮开始录音,松开发送的功能,因此为了实现这些功能就需要自己写一个Button来解决问题,下面小编给大... 目录Button 实现原理1. Surface 的作用(关键)2. InteractionSource3.

Android NDK版本迭代与FFmpeg交叉编译完全指南

《AndroidNDK版本迭代与FFmpeg交叉编译完全指南》在Android开发中,使用NDK进行原生代码开发是一项常见需求,特别是当我们需要集成FFmpeg这样的多媒体处理库时,本文将深入分析A... 目录一、android NDK版本迭代分界线二、FFmpeg交叉编译关键注意事项三、完整编译脚本示例四

Android与iOS设备MAC地址生成原理及Java实现详解

《Android与iOS设备MAC地址生成原理及Java实现详解》在无线网络通信中,MAC(MediaAccessControl)地址是设备的唯一网络标识符,本文主要介绍了Android与iOS设备M... 目录引言1. MAC地址基础1.1 MAC地址的组成1.2 MAC地址的分类2. android与I