avatar
童琦杰
Aug 19, 2018Technology

Android - AccessibilityService

服务配置文件

其中packageNames属性指定需要监视的程序包名,例如QQ(com.tencent.mobileqq),微信(com.tencent.mm),指定多个包名用逗号分隔。

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:canRetrieveWindowContent="true"
    android:description="@string/service_description"
    android:notificationTimeout="100"
    android:packageNames="com.tencent.mobileqq,com.tencent.mm" />

创建服务类

服务类继承于基类AccessibilityService

方法onServiceConnected在辅助服务开关打开时触发

方法onUnbind在辅助服务开关关闭时触发

方法onAccessibilityEvent在有事件时触发,辅助服务主要逻辑在该方法中实现

kotlin
import android.accessibilityservice.AccessibilityService
import android.content.Intent
import android.util.Log
import android.view.accessibility.AccessibilityEvent

class AutoVoiceService : AccessibilityService() {

    override fun onServiceConnected() {
        Log.i("AccessibilityService", "Service Connected")
        super.onServiceConnected()
    }

    override fun onUnbind(intent: Intent?): Boolean {
        Log.i("AccessibilityService", "Service Discounted")
        return super.onUnbind(intent)
    }

    override fun onInterrupt() {
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        Log.i("AccessibilityService", "Event Triggered")
    }
}

修改AndroidManifest.xml

属性name指定创建的服务类

属性resource指定服务配置文件

需要注意一点:区分大小写

xml
<service
    android:name=".AutoVoiceService"
    android:description="@string/service_description"
    android:enabled="true"
    android:exported="true"
    android:label="@string/app_name"
    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/auto_voice_accessibility_service" />
</service>
© 2015-2022 tongqijie.com 版权所有沪ICP备17000682号