使用android辅助服务监听Activity打开

1.添加权限

<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />

2.注册Service

<service
            android:name=".AutoFocusAccessibilityService"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
            <intent-filter>
                <action android:name="android.accessibilityservice.AccessibilityService" />
            intent-filter>
            <meta-data
                android:name="android.accessibilityservice"
                android:resource="@xml/accessibility_service_config" />
        service>

3.Application中设置权限

Settings.Secure.putString(getContentResolver(),
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
                "com.siviton.systemui/com.siviton.systemui.AutoFocusAccessibilityService");

        Settings.Secure.putInt(getContentResolver(),
                Settings.Secure.ACCESSIBILITY_ENABLED, 1);

4.添加xml配置


<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:accessibilityEventTypes="typeWindowStateChanged"
    android:accessibilityFeedbackType="feedbackGeneric"
    android:notificationTimeout="100"
    android:packageNames="com.siviton.autofocus"/>

5.核心Service


public class AutoFocusAccessibilityService extends AccessibilityService {
    private static final String TAG = AutoFocusAccessibilityService.class.getSimpleName();
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        Log.d(TAG, "onAccessibilityEvent event:" + event);
        // 处理 Accessibility 事件
        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            // 获取当前窗口的类名
            CharSequence currentClassName = event.getClassName();

            // 判断是否为目标 Activity 的类名
            if ("com.siviton.autofocus.ui.AutoFocusActivity".contentEquals(currentClassName)) {
                // 目标 Activity 的状态发生变化
                // 在这里执行你的逻辑
            }
        }
    }

    @Override
    public void onInterrupt() {

    }
}

你可能感兴趣的:(android,java,Accessibility)