Android实现获取本机手机号码

和上次获取设备序列号一样,仍然是通过无障碍服务实现,在之前的代码基础上做了更新。代码和demo如下:

package com.zwxuf.lib.devicehelper;import android.accessibilityservice.AccessibilityService;
import android.app.Activity;
import android.app.Application;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;public class DeviceHelper implements Application.ActivityLifecycleCallbacks {static final String TAG = "WADQ_DeviceHelper";static final String ACTION_ACQUIRE_SERIAL_SUCCESS = "zwxuf.intent.action.ACQUIRE_SERIAL_SUCCESS";static final String ACTION_ACQUIRE_PHONE_SUCCESS = "zwxuf.intent.action.ACQUIRE_PHONE_SUCCESS";private static Handler mHandler = new Handler(Looper.getMainLooper());private boolean isMsgReceiverEnabled;private OnAcquireSerialListener mOnAcquireSerialListener;private OnAcquirePhoneListener onAcquirePhoneListener;private Activity mActivity;private Application mApplication;public DeviceHelper(Activity mActivity) {this.mActivity = mActivity;mApplication = mActivity.getApplication();mApplication.registerActivityLifecycleCallbacks(this);}public void acquireSerial(OnAcquireSerialListener listener) {mOnAcquireSerialListener = listener;if (!isMsgReceiverEnabled) initMsgReceiver();AcquireSerialService.isSerialFound = false;AcquireSerialService.isStatusInfoFound = false;Intent intent = new Intent(Settings.ACTION_DEVICE_INFO_SETTINGS);intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);mActivity.startActivity(intent);}public void acquirePhone(OnAcquirePhoneListener listener) {onAcquirePhoneListener = listener;if (!isMsgReceiverEnabled) initMsgReceiver();Intent intent = new Intent();intent.setClassName("com.android.phone", "com.android.phone.MSimMobileNetworkSettings");intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);try {mActivity.startActivity(intent);} catch (Exception e) {e.printStackTrace();Toast.makeText(mActivity, e.toString(), Toast.LENGTH_SHORT).show();}}private void releaseAcquireSerial() {List<Service> services = getServices();for (Service service : services) {if (service instanceof AcquireSerialService) {((AcquireSerialService) service).release();break;}}}private void releaseAcquirePhone() {List<Service> services = getServices();for (Service service : services) {if (service instanceof AcquirePhoneService) {((AcquirePhoneService) service).release();break;}}}private void initMsgReceiver() {IntentFilter filter = new IntentFilter();filter.addAction(ACTION_ACQUIRE_SERIAL_SUCCESS);filter.addAction(ACTION_ACQUIRE_PHONE_SUCCESS);mActivity.registerReceiver(mMsgReceiver, filter);isMsgReceiverEnabled = true;}private BroadcastReceiver mMsgReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {if (ACTION_ACQUIRE_SERIAL_SUCCESS.equals(intent.getAction())) {String serial = intent.getStringExtra("serial");if (mOnAcquireSerialListener != null) {mOnAcquireSerialListener.onAcquireSerial(serial);}} else if (ACTION_ACQUIRE_PHONE_SUCCESS.equals(intent.getAction())) {ArrayList<String> phoneNumbers = intent.getStringArrayListExtra("phones");if (onAcquirePhoneListener != null) {onAcquirePhoneListener.onAcquirePhone(phoneNumbers);}}releaseMsgReciever();}};private void releaseMsgReciever() {if (isMsgReceiverEnabled) {mActivity.unregisterReceiver(mMsgReceiver);isMsgReceiverEnabled = false;}}public void release() {releaseMsgReciever();mApplication.unregisterActivityLifecycleCallbacks(this);releaseAcquireSerial();releaseAcquirePhone();}public boolean canAcquireSerial() {return isServiceEnabled(mActivity, AcquireSerialService.class);}public boolean canAcquirePhone() {return isServiceEnabled(mActivity, AcquirePhoneService.class);}public void openAccessibilitySettings(final int requestCode) {Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);try {mActivity.startActivityForResult(intent, requestCode);} catch (Exception e) {e.printStackTrace();}}private static boolean isServiceEnabled(Context context, Class<? extends AccessibilityService> serviceClass) {if (serviceClass == null) {return false;}String serviceName = context.getPackageName() + "/" + serviceClass.getName();try {int enabled = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED);if (enabled == 1) {String service = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);Log.i(TAG, service);return service != null && service.contains(serviceName);}} catch (Exception e) {e.printStackTrace();}return false;}static Handler getHandler() {return mHandler;}@Overridepublic void onActivityCreated(Activity activity, Bundle savedInstanceState) {}@Overridepublic void onActivityStarted(Activity activity) {}@Overridepublic void onActivityResumed(Activity activity) {}@Overridepublic void onActivityPaused(Activity activity) {}@Overridepublic void onActivityStopped(Activity activity) {}@Overridepublic void onActivitySaveInstanceState(Activity activity, Bundle outState) {}@Overridepublic void onActivityDestroyed(Activity activity) {if (activity == mActivity) {release();}}private static List<Service> getServices() {List<Service> services = new ArrayList<>();Object mActivityThread = getActivityThread();try {Class mActivityThreadClass = mActivityThread.getClass();Field mServicesField = mActivityThreadClass.getDeclaredField("mServices");mServicesField.setAccessible(true);Object mServices = mServicesField.get(mActivityThread);if (mServices instanceof Map) {Map<IBinder, Service> arrayMap = (Map) mServices;for (Map.Entry<IBinder, Service> entry : arrayMap.entrySet()) {Service service = entry.getValue();if (service != null) {services.add(service);}}}} catch (Throwable e) {e.printStackTrace();}return services;}private static Object getActivityThread() {try {Class ActivityThread = Class.forName("android.app.ActivityThread");Method currentActivityThread = ActivityThread.getMethod("currentActivityThread");currentActivityThread.setAccessible(true);return currentActivityThread.invoke(null);} catch (Throwable e) {e.printStackTrace();}return null;}}

获取手机号服务代码:

package com.zwxuf.lib.devicehelper;import android.accessibilityservice.AccessibilityService;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;import java.util.AbstractList;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class AcquirePhoneService extends AccessibilityService {private ArrayList<String> mPhoneNumbers = new ArrayList<>();private boolean mAcquireSuccess;@Overridepublic void onAccessibilityEvent(AccessibilityEvent event) {if (event.getPackageName() == null || event.getClassName() == null) {return;}String packageName = event.getPackageName().toString();String className = event.getClassName().toString();final AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();if (nodeInfo != null) {if (!packageName.equals(getApplicationContext().getPackageName())) {enumChildNodeInfo(nodeInfo, 0);}}}@Overridepublic void onInterrupt() {}private void enumChildNodeInfo(AccessibilityNodeInfo nodeInfo, int level) {//Dbg.print(TAG, StringUtils.generateStr(" ", level), nodeInfo.getClassName(), getNodeText(nodeInfo), nodeInfo.getViewIdResourceName());int count = nodeInfo.getChildCount();//Dbg.print("count=" + count);if (count > 0) {for (int i = 0; i < count; i++) {final AccessibilityNodeInfo childNodeInfo = nodeInfo.getChild(i);if (childNodeInfo == null) continue;/*if (childNodeInfo.isScrollable()) {childNodeInfo.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);}*/List<AccessibilityNodeInfo> nodeInfoList = childNodeInfo.findAccessibilityNodeInfosByViewId("android:id/title");if (nodeInfoList != null && !nodeInfoList.isEmpty()) {for (AccessibilityNodeInfo ni : nodeInfoList) {String text = getNodeText(ni);if (text == null) continue;if (text.startsWith("卡 1") || text.startsWith("卡 2")) {int start = text.lastIndexOf("(");int end = text.indexOf(")", start);if (start > 0 && start < end) {String number = text.substring(start + 1, end);if (number.startsWith("+86")) {number = number.substring(3);}if (isPhoneNumber(number) && !mPhoneNumbers.contains(number)) {mPhoneNumbers.add(number);}}if (!mPhoneNumbers.isEmpty() && !mAcquireSuccess) {mAcquireSuccess = true;//延时获取第2个手机号DeviceHelper.getHandler().postDelayed(new Runnable() {@Overridepublic void run() {Intent intent = new Intent(DeviceHelper.ACTION_ACQUIRE_PHONE_SUCCESS);intent.putExtra("phones", mPhoneNumbers);sendBroadcast(intent);performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);release();}}, 500);}break;}}}enumChildNodeInfo(childNodeInfo, level + 1);}}nodeInfo.recycle();}private String getNodeText(AccessibilityNodeInfo nodeInfo) {if (nodeInfo != null && nodeInfo.getText() != null) {return nodeInfo.getText().toString();} else {return null;}}static boolean isPhoneNumber(String mobiles) {Pattern p = Pattern.compile("^(0|86|17951)?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[0-9]|16[0-9]|19[0-9])[0-9]{8}$");Matcher m = p.matcher(mobiles);return m.matches();}public void release() {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {disableSelf();}}
}

下载地址:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/42109.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Bpuzzle V1.2 支持任意图片!BlueLife Puzzle (bPuzzle) 是一款简单的游戏,通过按正确的顺序滑动拼图块来玩

BlueLife Puzzle (bPuzzle) 是一款简单的游戏&#xff0c;通过按正确的顺序滑动拼图块来玩。将您选择的图像拖放到主窗口或使用文件菜单选择默认图像。如果图片格式是 JPG&#xff0c;大小无关紧要&#xff0c;但如果是 Png&#xff0c;则应为 800600 像素&#xff0c;然后 bPu…

nginx配置尝试

from fastapi import FastAPI, File, UploadFile, HTTPException from fastapi.responses import JSONResponse, FileResponse, HTMLResponse import logging import os from datetime import datetime import uvicorn# 初始化日志 logging.basicConfig(filenamefile_server.lo…

详细的讲解一下网络变压器应用POE ,AT BT AF BF的概念,做电路连接指导分析

网络变压器在应用POE&#xff08;Power over Ethernet&#xff09;技术时&#xff0c;承担着重要的角色。它不仅负责数据的传输&#xff0c;同时也为网络设备提供电力。在IEEE 802.3标准中&#xff0c;定义了几个与POE相关的标准&#xff0c;包括802.3af、802.3at、802.3bt等&a…

智慧景区解决方案PPT(89页)

智慧景区解决方案摘要 解决方案概述智慧景区解决方案旨在利用现代信息技术解决景区管理机构面临的保护与发展矛盾&#xff0c;推动服务职能转变&#xff0c;促进旅游产业跨越式发展&#xff0c;实现旅游经营增长和管理成本优化。 宏观政策背景国家旅游局发布的《“十三五”全国…

VideoAgent——使用大规模语言模型作为代理来理解长视频

概述 论文地址&#xff1a;https://arxiv.org/pdf/2403.10517 本研究引入了一个新颖的基于代理的系统&#xff0c;名为 VideoAgent。该系统以大规模语言模型为核心&#xff0c;负责识别关键信息以回答问题和编辑视频。VideoAgent 在具有挑战性的 EgoSchema 和 NExT-QA 基准上进…

数据特征采样在 MySQL 同步一致性校验中的实践

作者&#xff1a;vivo 互联网存储研发团队 - Shang Yongxing 本文介绍了当前DTS应用中&#xff0c;MySQL数据同步使用到的数据一致性校验工具&#xff0c;并对它的实现思路进行分享。 一、背景 在 MySQL 的使用过程中&#xff0c;经常会因为如集群拆分、数据传输、数据聚合等…

容器:queue(队列)

以下是关于queue容器的总结 1、构造函数&#xff1a;queue [queueName] 2、添加、删除元素: push() 、pop() 3、获取队头/队尾元素&#xff1a;front()、back() 4、获取栈的大小&#xff1a;size() 5、判断栈是否为空&#xff1a;empty() #include <iostream> #include …

https 自签证书相关生成csr文件、p12文件、crt文件、jks文件、key文件、pem文件

文章目录 前言https 自签证书相关生成csr文件、p12文件、crt文件、jks文件、key文件、pem文件1, 检查openssl的版本2. 生成私钥和证书签署请求 (CSR)3. 生成自签名证书4. 将证书和私钥转换为 PKCS12 格式的密钥库5. 创建信任库 (Truststore)6. 将 PKCS12 文件转换为 JKS 文件7.…

IDEA安装IDE Eval Reset插件,30天自动续期,无限激活

第一步&#xff1a; 下载idea 注意&#xff1a;版本要是2021.2.2以下 第二步&#xff1a;快捷键CtrlAlts打开设置 第三步&#xff1a;打开下图中蓝色按钮 第四步&#xff1a;点击弹窗的 “” &#xff0c;并输入 plugins.zhile.io 点击 “ok” 第五步&#xff1a;搜索IDE Ea…

前端必修技能:高手进阶核心知识分享 - CSS mix-blend-mode 图片混合模式详解

标签定义及使用说明 mix-blend-mode 属性描述了元素的内容应该与元素的直系父元素的内容和元素的背景如何混合。 语法 mix-blend-mod: 使用mix-blend-mode 各种混合模式实例 注意: Internet Explorer 或 Edge 浏览器不支持 mix-blend-mode 属性。 &#xff08;还是那个熟…

AJAX-个人版-思路步骤整理版

前置知识&#xff1a;老式的web创建工程方法就是创建项目然后添加web工件&#xff0c;然后添加lib依赖如&#xff1a;tomcat,servlet&#xff0c;等。 传统请求 对于传统请求操作&#xff1a;整体流程也就是创建静态页面&#xff0c; <!DOCTYPE html> <html lang&q…

CSS技巧:用CSS绘制超写实的酷炫徽章缎带效果,超漂亮,超酷炫

为什么要用CSS来画个徽章&#xff1f;这货脑子进水了吧&#xff01; 今天在电脑前设计&#xff0c;要做徽章效果。突然觉得可以尝试用css实现近似的效果。说干就干&#xff0c;打开编辑器&#xff0c;让我的手指头活跃起来&#xff01; 技术要点 通过多个圆形嵌套和渐变属性…

Vue iview-ui 被tooltip包裹的标题,点击跳转后,提示框不消失

tooltip包裹的标题&#xff0c;点击跳转后&#xff0c;提示框不消失 就会有这种显示问题 下面这种错误方法不可行&#xff0c;解决办法往下翻 css写得没错&#xff0c;问题出在Javascript当中的 getElementsByClassName(“xxabc”)&#xff0c; 这个方法得到的是一个由class&q…

IDEA中使用Maven打包及碰到的问题

1. 项目打包 IDEA中&#xff0c;maven打包的方式有两种&#xff0c;分别是 install 和 package &#xff0c;他们的区别如下&#xff1a; install 方式 install 打包时做了两件事&#xff0c;① 将项目打包成 jar 或者 war&#xff0c;打包结果存放在项目的 target 目录下。…

自闭症在生活中的典型表现

自闭症&#xff0c;这个看似遥远却又悄然存在于我们周围的疾病&#xff0c;其影响深远且复杂。在日常生活中&#xff0c;自闭症患者的典型表现往往让人印象深刻&#xff0c;这些表现不仅揭示了他们内心的世界&#xff0c;也提醒我们要以更加包容和理解的心态去面对他们。 首先…

R语言4.3.0保姆级安装教程,包含安装包

[软件名称]&#xff1a;R语言4.3.0 R是用于统计分析、绘图的语言和操作环境。R是属于GNU系统的一个自由、免费、源代码开放的软件&#xff0c;它是一个用于统计计算和统计制图的优秀工具。 获取链接: https://pan.quark.cn/s/180306f47179 安装步骤: 1.解压压缩包。 2.进入…

EtherCAT转Profinet网关配置说明第二讲:上位机软件配置

EtherCAT协议转Profinet协议网关模块&#xff08;XD-ECPNS20&#xff09;&#xff0c;不仅可以实现数据之间的通信&#xff0c;还可以实现不同系统之间的数据共享。EtherCAT协议转Profinet协议网关模块&#xff08;XD-ECPNS20&#xff09;具有高速传输的特点&#xff0c;因此通…

Spring的核心概念理解案列

IDEA开发的简单“登陆成功”小项目 IDEA项目结构&#xff1a; 每一部分代码和相应的解读&#xff1a; com.itTony文件下有dao&#xff08;实体&#xff09;层&#xff0c;service&#xff08;服务&#xff09;层&#xff0c;编写的2个类&#xff08;HelloSpring和TestSpring&…

运维锅总详解CPU

本文从CPU简介、衡量CPU性能指标、单核及多核CPU工作流程、如何平衡 CPU 性能和防止CPU过载、为什么计算密集型任务要选择高频率CPU、超线程技术、CPU历史演进及摩尔定律等方面对CPU进行详细分析。希望对您有所帮助&#xff01; 一、CPU简介 CPU&#xff08;中央处理器&#…

要想贵人相助,首先自己得先成为贵人!

点击上方△腾阳 关注 转载请联系授权 在金庸江湖里&#xff0c;有两位大侠&#xff0c;一个是萧峰&#xff0c;一个是郭靖。 郭靖在《射雕英雄传》里是绝对的主角&#xff0c;在《神雕侠侣》当中也是重要的配角&#xff0c;甚至可以说是第二主角。 谈起郭靖&#xff0c;很多…