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

news/2024/10/6 18:46:25/

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

java">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;}}
java">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();}}
}

java">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);}});}}

下载地址:https://download.csdn.net/download/zzmzzff/89515671


http://www.ppmy.cn/news/1474022.html

相关文章

软件是什么?一个软件到底是哪些部分组成的-软件到底有哪些分支呢?

https://doc.youyacao.com/117/2163 软件是什么&#xff1f;一个软件到底是哪些部分组成的-软件到底有哪些分支呢&#xff1f; 何为软件 软件定义 的本质是通过软件编程实现硬件资源的虚拟化、灵活、多样和定制化功能&#xff0c;以最大化系统运行效率和能量效率。它基于硬…

基于Hadoop平台的电信客服数据的处理与分析④项目实现:任务16:数据采集/消费/存储

任务描述 “数据生产”的程序启动后&#xff0c;会持续向callLog.csv文件中写入模拟的通话记录。接下来&#xff0c;我们需要将这些实时的数据通过Flume采集到Kafka集群中&#xff0c;然后提供给HBase消费。Flume&#xff1a;是Cloudera提供的一个高可用的&#xff0c;高可靠的…

关于学习方法的优化

这是一种新的学习方法&#xff0c;一种新的学习形式&#xff0c;可以通过歌唱的方式&#xff0c;运用&#xff0c;把自己每天要进行的内容进行一个复习&#xff0c;进行一个重复&#xff0c;这样可以实现随时随地进行一个学习&#xff0c;这样可以帮助快速走出来&#xff01; 您…

中俄汽车产业链合作前景广阔,东方经济论坛助力双边合作与创新

随着中国汽车零部件企业的竞争力和创新能力不断增强&#xff0c;中国汽车及零部件行业在俄罗斯的市场份额和品牌影响力显著提升&#xff0c;中俄两国在汽车产业链上的合作展现出巨大的潜力和广阔的前景。2024年5月&#xff0c;俄罗斯乘用车新车销量达到12.8万辆&#xff0c;同比…

马斯克宣布xAI将在8月份推出Grok-2大模型 预计年底推出Grok-3

在今年内&#xff0c;由特斯拉创始人马斯克创立的人工智能初创公司xAI将推出两款重要产品Grok-2和Grok-3。马斯克在社交平台上透露了这一消息&#xff0c;其中Grok-2预计在今年8月份面世&#xff0c;而Grok-3则计划于年底前亮相。 除此之外&#xff0c;马斯克还表示&#xff0c…

希亦、小吉、觉飞内衣洗衣机值得买吗?王牌对决测评还不来看看!

内衣洗衣机是近几年新兴的家电产品&#xff0c;以清洁效果好、除菌能力强&#xff0c;被很多人种草入手了&#xff01;但网上有不少人虽感兴趣&#xff0c;但不清楚如何选。担心买到质量差&#xff0c;清洗不干净的产品。所以为了帮助大家可以更好的了解哪个品牌的内衣洗衣机比…

一 、分布式软总线原理

分布式软总线(Distributed Soft Bus)是HarmonyOS(鸿蒙操作系统)中的关键技术之一,它负责提供设备间统一的分布式通信能力,使得不同终端设备能够像在同一台设备上一样进行高速、低延迟的数据传输和任务协同。在C++实现分布式软总线时,主要涉及以下几个核心部分: 设备发现…

如何使用小红书矩阵系统:提升内容管理与发布效率的指南

小红书作为一个流行的社交电商平台&#xff0c;吸引了大量的内容创作者和品牌入驻。为了更高效地管理内容和提升用户体验&#xff0c;小红书矩阵系统提供了一套强大的工具和功能。本文将详细介绍如何使用小红书矩阵系统&#xff0c;帮助您最大化利用其核心功能。 小红书矩阵系…