Android10以上实现获取设备序列号功能

Android10以上实现获取设备唯一标识,目前只支持华为和荣耀设备。实现原理:通过无障碍服务读取序列号界面。

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";private static Handler mHandler = new Handler(Looper.getMainLooper());private boolean isMsgReceiverEnabled;private OnAcquireSerialListener mOnAcquireSerialListener;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);}private void releaseAcquireSerial() {List<Service> services = getServices();for (Service service : services) {if (service instanceof AcquireSerialService) {((AcquireSerialService) service).release();break;}}}private void initMsgReceiver() {IntentFilter filter = new IntentFilter(ACTION_ACQUIRE_SERIAL_SUCCESS);mActivity.registerReceiver(mMsgReceiver, filter);isMsgReceiverEnabled = true;}private BroadcastReceiver mMsgReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String serial = intent.getStringExtra("serial");if (mOnAcquireSerialListener != null) {mOnAcquireSerialListener.onAcquireSerial(serial);}releaseMsgReciever();}};private void releaseMsgReciever() {if (isMsgReceiverEnabled) {mActivity.unregisterReceiver(mMsgReceiver);isMsgReceiverEnabled = false;}}public void release() {releaseMsgReciever();mApplication.unregisterActivityLifecycleCallbacks(this);releaseAcquireSerial();}public boolean canAcquireSerial() {return isServiceEnabled(mActivity, AcquireSerialService.class);}public void openAcquireSerialSettings(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;}}
public class AcquireSerialService extends AccessibilityService {static boolean isStatusInfoFound;static boolean isSerialFound;@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(packageName, nodeInfo, 0);}}}@Overridepublic void onInterrupt() {}private Runnable mScrollRunnalbe;private void enumChildNodeInfo(String packageName, AccessibilityNodeInfo nodeInfo, int level) {int count = nodeInfo.getChildCount();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);}if (!isSerialFound) {String serial = getSerialByNodeInfo(packageName, childNodeInfo);if (serial != null && !serial.isEmpty()) {//获取到snLog.i(DeviceHelper.TAG, serial);Intent intent = new Intent(DeviceHelper.ACTION_ACQUIRE_SERIAL_SUCCESS);intent.putExtra("serial", serial);sendBroadcast(intent);performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);DeviceHelper.getHandler().postDelayed(new Runnable() {@Overridepublic void run() {performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);release();}}, 200);return;}enumChildNodeInfo(packageName, childNodeInfo, level + 1);}}}nodeInfo.recycle();}private String getSerialByNodeInfo(String packageName, AccessibilityNodeInfo nodeInfo) {if (nodeInfo.getText() == null) {return null;}String text = nodeInfo.getText().toString();if (text.equals("序列号")) {isStatusInfoFound = true;isSerialFound = true;if (mScrollRunnalbe != null) {DeviceHelper.getHandler().removeCallbacks(mScrollRunnalbe);mScrollRunnalbe = null;}return getValue(nodeInfo);} else if (packageName.equals("com.android.settings") && (text.equals("状态信息") || text.equals("状态消息")) && !isStatusInfoFound) {isStatusInfoFound = true;AccessibilityNodeInfo statusInfoParent = nodeInfo.getParent();while (statusInfoParent != null && !statusInfoParent.isClickable()) {statusInfoParent = statusInfoParent.getParent();}if (statusInfoParent != null) {final AccessibilityNodeInfo finalStatusInfoParent = statusInfoParent;DeviceHelper.getHandler().postDelayed(new Runnable() {@Overridepublic void run() {finalStatusInfoParent.performAction(AccessibilityNodeInfo.ACTION_CLICK);}}, 200);}}return null;}private String getValue(AccessibilityNodeInfo nodeInfo) {AccessibilityNodeInfo snLayout = nodeInfo.getParent();if (snLayout != null) {while (true) {List<AccessibilityNodeInfo> snSummaryList = snLayout.findAccessibilityNodeInfosByViewId("android:id/summary");if (snSummaryList != null && !snSummaryList.isEmpty()) {AccessibilityNodeInfo snSummary = snSummaryList.get(0);if (snSummary != null && snSummary.getText() != null) {return snSummary.getText().toString();}}snLayout = snLayout.getParent();if (snLayout == null) {break;}}}return null;}private String getNodeText(AccessibilityNodeInfo nodeInfo) {if (nodeInfo != null && nodeInfo.getText() != null) {return nodeInfo.getText().toString();} else {return null;}}public void release() {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {disableSelf();}}
}

public class MainActivity extends AppCompatActivity implements View.OnClickListener {private DeviceHelper mDeviceHelper;private TextView tv_serial, tv_phone;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv_serial = findViewById(R.id.tv_serial);mDeviceHelper = new DeviceHelper(this);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.bn_get_serial:getSerial();break;}}private void getSerial() {if (!mDeviceHelper.canAcquireSerial()) {new AlertDialog.Builder(this).setMessage("没有开启无障碍服务").setPositiveButton("去开启", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {mDeviceHelper.openAcquireSerialSettings(1000);}}).setNegativeButton("取消", null).create().show();return;}mDeviceHelper.acquireSerial(new OnAcquireSerialListener() {@Overridepublic void onAcquireSerial(String serial) {//Toast.makeText(MainActivity.this, serial, Toast.LENGTH_SHORT).show();tv_serial.setText("sn:" + serial);}});}}

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

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

相关文章

Zoom使用的基本步骤和注意事项

Zoom是一款功能强大的视频会议软件&#xff0c;广泛应用于远程办公、在线教育、团队协作等多个场景。以下是Zoom使用的基本步骤和注意事项&#xff1a; 一、注册与登录 注册Zoom账户&#xff1a; 访问Zoom官方网站&#xff08;如zoom.us&#xff09;&#xff0c;点击“注册”…

Android Enable 和clickable

setEnabled 使能控件 设置为false&#xff0c;该控件永远不会活动&#xff0c;不管设置为什么属性&#xff0c;都无效&#xff1b; 设置为true&#xff0c;表明激活该控件&#xff0c;控件处于活动状态&#xff0c;处于活动状态&#xff0c;就能响应事件了&#xff0c;比如触摸…

mybatis实现动态sql

第一章、动态SQL MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验&#xff0c;你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格&#xff0c;还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特…

2024北京大健康展,北京健康生活产品展览会十月举办

2024北京健博会&#xff0c;立足北京&#xff0c;效应辐射全国买方市场&#xff0c;助力健康中国事业建设&#xff1b; 2024第11届中国&#xff08;北京&#xff09;国际大健康产业博览会 The 2024 China (Beijing) International Health Service Expo 时间&#xff1a;2024年…

华为 RIP 协议中 RIP 兼容版本、RIPv1、RIPv2 在收发 RIP 报文时的区别

华为 RIP 协议中 RIP 兼容版本、RIPv1、RIPv2 的区别 为了更好地支持实际环境中路由器对 RIP 的支持&#xff0c;华为 VRP 平台具有一个兼容版本&#xff0c;默认情况下启动 RIP 进程后&#xff0c;如果没有配置 RIP 版本&#xff0c;该版本就为兼容版本&#xff0c;对 versio…

[ C++ ] 深入理解模板( 进 阶 )

目录 非类型模板参数 类模板没有实例化的情况 模板的特化 注意函数特化中遇到的问题 建议&#xff1a;&#xff08;直接使用函数重载&#xff09; 类模板特化 全特化 偏特化 偏特化有以下两种表现方式&#xff1a; 部分特化&#xff08;将模板参数类表中的一部分参数特化…

vue this.$refs加变量名

想动态获取$refs&#xff0c;我们可以用模板字符串来动态绑定ref的值。代码如下&#xff1a; this.$refs[${this.treeQueFlag}].setCheckedNodes([]); $refs后面拼变量&#xff0c;vue动态给$refs赋值_vue ref动态赋值-CSDN博客

旅游系统(附管理端+前台)PHP源码

一. 前言 今天小编给大家带来了一款可学习&#xff0c;可商用的&#xff0c;旅游系统 源码&#xff0c;支持二开&#xff0c;无加密。支持景点管理&#xff0c;登录&#xff0c;景点预定&#xff0c;意见反馈&#xff0c;统计等功能。详细界面和功能见下面视频演示。 二. 视频…

【flutter问题记录】 无效的源发行版:17

问题描述 在看开源项目的时候&#xff0c;clone下来后一直编译失败&#xff0c;提示&#xff1a;无效的源发行版:17&#xff0c;看描述大概是jdk的版本问题&#xff0c;但是在Android studio各种指定都无用&#xff0c;网上资料也没有flutter项目的解决方案&#xff0c;最后在…

在Spring MVC框架中,如何处理HTTP请求和响应?

在Spring MVC框架中&#xff0c;HTTP请求和响应的处理是通过一系列组件和流程来完成的。以下是Spring MVC处理HTTP请求和响应的主要步骤&#xff1a; 用户发起请求&#xff1a; 用户在客户端&#xff08;如浏览器&#xff09;上发起一个HTTP请求&#xff0c;这个请求被发送到服…

广州自闭症机构哪家好?

在广州&#xff0c;众多的自闭症康复机构中&#xff0c;星贝育园自闭症儿童康复学校以其独特的优势脱颖而出。 一、专业的师资团队 我们拥有一支经验丰富、专业素养极高的师资队伍。每位老师都经过严格的专业培训&#xff0c;深入了解自闭症儿童的特点和需求。他们不仅具…

深入挖掘海外快手kwai ads推广巴西slots手游广告独家优势

深入挖掘海外快手kwai ads推广巴西slots手游广告独家优势 在数字化时代&#xff0c;广告投放已成为各行各业不可或缺的一部分&#xff0c;特别是在游戏行业&#xff0c;如何有效地推广游戏产品&#xff0c;吸引玩家的眼球&#xff0c;成为了每一个游戏开发商和广告主所关注的焦…

假设性文档嵌入 HyDE:大模型 + 对比学习,从关键词相似度搜索到语义搜索

假设性文档嵌入 HyDE&#xff1a;大模型 对比学习&#xff0c;从关键词相似度搜索到语义搜索 提出背景流程图解法拆解类比1. 单一文档嵌入空间的搜索2. 指令跟随型语言模型&#xff08;InstructLM&#xff09;的引入3. 生成文档的嵌入编码 提出背景 论文&#xff1a;https://…

python怎么样将一段程序无效掉

1、python中可以用注释屏蔽一段语句&#xff0c;具体方法如下&#xff0c;首先打开一段python的示例程序&#xff1a; 2、然后单行注释的方法是在语句前面加上#&#xff0c;程序运行后添加注释的地方的语句会被自动跳过&#xff0c;这里可以看到将打印变量a的语句添加注释就没有…

vue处理重复请求

处理方法记录第一次的请求时间-后面的请求时间&#xff0c;判断间隔时间提示请求重复 // 登录方法 定义repeatSubmit属性控制是否重复请求 export function login(username, password, code, uuid) {const data {username,password,code,uuid}return request({url: /login,he…

前端css性能优化

前端css性能优化 1. 减少样式表数量和压缩文件大小&#xff1a; 通过合并多个样式表、删除未使用的样式、压缩样式表等方式来减少样式表数量和大小&#xff0c;从而减少网络请求和提高加载速度。 通常来说&#xff0c;样式文件会被浏览器缓存&#xff0c;进入到其他页面样式文件…

在 C++中,如何实现高效的多线程并发编程以处理大规模数据计算,同时避免常见的竞态条件和死锁问题?

在 C 中&#xff0c;可以使用以下几种方法来实现高效的多线程并发编程以处理大规模数据计算&#xff0c;并避免常见的竞态条件和死锁问题&#xff1a; 使用互斥锁&#xff1a;使用 std::mutex 类型的互斥锁来保护共享数据的访问。在访问共享数据之前&#xff0c;线程先要获取互…

二叉树 Leetcode 101 对称二叉树

二叉树 Leetcode 101 对称二叉树 Leetcode 101 要点&#xff1a;1.比较的是左右子树是否相同&#xff0c;不是节点的左右孩子&#xff1b; 2.左子树左右中遍历&#xff0c;右子树右左中遍历&#xff1b; 3.灵活递归。 /*** Definition for a binary tree node.* struct Tree…

【实验室精选】PFA反应瓶带鼓泡球 高效气体鼓泡 化学分析优选

PFA反应瓶带鼓泡球是一种特殊设计的实验室容器&#xff0c;它集成了鼓泡球和PFA&#xff08;全氟烷氧基&#xff09;材料的反应瓶&#xff0c;用于气体的鼓泡和液体的混合。以下是它的一些特点和用途&#xff1a; 特点&#xff1a; 鼓泡球设计&#xff1a;鼓泡球周围布满小孔&…

安装realsenseSDK2.0

1、创造工作空间并进入 mkdir ros_ws cd ros_ws/ 2、克隆librealsense git clone https://github.com/IntelRealSense/librealsense cd librealsense 3、安装依赖项 sudo apt-get install libssl-dev sudo apt-get install libusb-1.0-0-dev sudo apt-get install libudev…