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实现在线预览office文档的示例详解

《Android实现在线预览office文档的示例详解》在移动端展示在线Office文档(如Word、Excel、PPT)是一项常见需求,这篇文章为大家重点介绍了两种方案的实现方法,希望对大家有一定的... 目录一、项目概述二、相关技术知识三、实现思路3.1 方案一:WebView + Office Onl

Android实现两台手机屏幕共享和远程控制功能

《Android实现两台手机屏幕共享和远程控制功能》在远程协助、在线教学、技术支持等多种场景下,实时获得另一部移动设备的屏幕画面,并对其进行操作,具有极高的应用价值,本项目旨在实现两台Android手... 目录一、项目概述二、相关知识2.1 MediaProjection API2.2 Socket 网络

Android实现悬浮按钮功能

《Android实现悬浮按钮功能》在很多场景中,我们希望在应用或系统任意界面上都能看到一个小的“悬浮按钮”(FloatingButton),用来快速启动工具、展示未读信息或快捷操作,所以本文给大家介绍... 目录一、项目概述二、相关技术知识三、实现思路四、整合代码4.1 Java 代码(MainActivi

Android Mainline基础简介

《AndroidMainline基础简介》AndroidMainline是通过模块化更新Android核心组件的框架,可能提高安全性,本文给大家介绍AndroidMainline基础简介,感兴趣的朋... 目录关键要点什么是 android Mainline?Android Mainline 的工作原理关键

基于Java实现回调监听工具类

《基于Java实现回调监听工具类》这篇文章主要为大家详细介绍了如何基于Java实现一个回调监听工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录监听接口类 Listenable实际用法打印结果首先,会用到 函数式接口 Consumer, 通过这个可以解耦回调方法,下面先写一个

如何解决idea的Module:‘:app‘platform‘android-32‘not found.问题

《如何解决idea的Module:‘:app‘platform‘android-32‘notfound.问题》:本文主要介绍如何解决idea的Module:‘:app‘platform‘andr... 目录idea的Module:‘:app‘pwww.chinasem.cnlatform‘android-32

Android实现打开本地pdf文件的两种方式

《Android实现打开本地pdf文件的两种方式》在现代应用中,PDF格式因其跨平台、稳定性好、展示内容一致等特点,在Android平台上,如何高效地打开本地PDF文件,不仅关系到用户体验,也直接影响... 目录一、项目概述二、相关知识2.1 PDF文件基本概述2.2 android 文件访问与存储权限2.

Android Studio 配置国内镜像源的实现步骤

《AndroidStudio配置国内镜像源的实现步骤》本文主要介绍了AndroidStudio配置国内镜像源的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、修改 hosts,解决 SDK 下载失败的问题二、修改 gradle 地址,解决 gradle

在Android平台上实现消息推送功能

《在Android平台上实现消息推送功能》随着移动互联网应用的飞速发展,消息推送已成为移动应用中不可或缺的功能,在Android平台上,实现消息推送涉及到服务端的消息发送、客户端的消息接收、通知渠道(... 目录一、项目概述二、相关知识介绍2.1 消息推送的基本原理2.2 Firebase Cloud Me

Android中Dialog的使用详解

《Android中Dialog的使用详解》Dialog(对话框)是Android中常用的UI组件,用于临时显示重要信息或获取用户输入,本文给大家介绍Android中Dialog的使用,感兴趣的朋友一起... 目录android中Dialog的使用详解1. 基本Dialog类型1.1 AlertDialog(