使用 AccessibilityService 获取手机屏幕显示的Activity
1、重新AccessibilityService (没有这么简单)
class SimulatedClickService : AccessibilityService() {
@RequiresApi(api = Build.VERSION_CODES.N)
override fun onAccessibilityEvent(event: AccessibilityEvent) {
var name = event.getClassName().toString();
if (name.contains("com.")) {
if (name.contains(event.packageName)) {
name = name.replace(event.packageName.toString(), "");
name = name.replace("..", "")
if (name.get(0) == '.')
name = name.substring(1);
}
activityName = name
//这就获取到了包名和top顶部的activity
//tip?.text="${event.packageName}${name}" // 开启悬浮窗 可以显示到窗口上
loge("${event.packageName}${name}")
}
/**
* 中断服务的回调
*/
override fun onInterrupt() {
}
/**
* 当服务启动时的回调,可以做一些初始化操作
*/
@RequiresApi(api = Build.VERSION_CODES.N)
override fun onServiceConnected() {
}
}
2、配置AccessibilityService在AndroidManifest
android:name=".SimulatedClickService"
android:enabled="true"
android:exported="true"
android:label="@string/click_window_screen"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
android:name="android.accessibilityservice"
android:resource="@xml/accessibility_service_config" />
3、配置AccessibilityService在xml
在res下的xml文件下新建accessibility_service_config.xml
<?xml version="1.0" encoding="utf-8"?> <accessibility-service xmlns:android="http://schemas.android.com/apk/res/android" android:accessibilityEventTypes="typeAllMask" android:accessibilityFeedbackType="feedbackGeneric" android:accessibilityFlags="flagDefault" android:canPerformGestures="true" android:description="@string/app_name" android:packageNames="com.duiyi.simulatedclick" />
想知道里面的具体含义可以去百度,百度一大堆
4、开启无障碍
@RequiresApi(api = Build.VERSION_CODES.M) fun startFloatingService() { if (!Settings.canDrawOverlays(this)) { startActivityForResult( Intent( Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse( "package:$packageName" ) ), 0x0002 ) } else { try { try { startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)) } catch (e: Exception) { Log.i(TAG, "start ACTION_ACCESSIBILITY_SETTINGS fail: " + e.message) startActivity(Intent(Settings.ACTION_SETTINGS)) } } }