kotlin使用辅助功能自动刷短视频
1.在文件AndroidManifest.xml里面添加 :
<service
android:name=".AutoService"
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/auto_refresh_config" />
</service>
2.在res目录下新建文件夹xml,再新建文件auto_refresh_config.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeWindowStateChanged|typeWindowContentChanged|typeNotificationStateChanged"
android:accessibilityFeedbackType="feedbackAllMask"
android:accessibilityFlags="flagDefault|flagRetrieveInteractiveWindows|flagIncludeNotImportantViews|flagReportViewIds"
android:canRetrieveWindowContent="true"
android:canRequestFilterKeyEvents="true"
android:description="@string/app_name"
android:canRequestEnhancedWebAccessibility="true"
android:notificationTimeout="20"
android:canPerformGestures="true" />
里面可以设置只在某个app上有作用
3.具体实现如下:
class AutoService : AccessibilityService() {
var isStop = false
val apks = "com.ss.android.ugc.aweme,com.ss.android.article.video,com.kwai.thanos,com.ss.android.article.news"
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
println("zzx===>onAccessibilityEvent event:"+event.toString())
if(apks.contains(event!!.packageName) && !isStop){
val autoThread = AutoThread()
autoThread.start()
}
}
override fun onInterrupt() {
}
inner class AutoThread:Thread(){
@RequiresApi(Build.VERSION_CODES.N)
override fun run() {
isStop = true
while (!Thread.interrupted()){
try {
val path = Path()
//下面的参数需要根据实际情况做调整
path.moveTo(200f, 600f);
path.lineTo(200f,0f);
val start = 100L
val duration = start+200
var callback = object : GestureResultCallback1(){
override fun onCompleted(gestureDescription: GestureDescription?) {
println("zzx===>touch complete")
}
override fun onCancelled(gestureDescription: GestureDescription?) {
println("zzx===>touch cancel")
}
}
gestureOnScreen(path,start,duration,callback)
Thread.sleep(5000)
}catch (ex:Exception){
ex.printStackTrace()
}
}
}
@RequiresApi(Build.VERSION_CODES.N)
protected fun gestureOnScreen(
path: Path?, startTime: Long, duration: Long,
callback: GestureResultCallback1?
) {
val builde = GestureDescription.Builder()
builde.addStroke(StrokeDescription(path!!, startTime, duration))
val gestureDescription = builde.build()
dispatchGesture(gestureDescription, callback, null)
}
}
}
注意:上面代码本人在android10原生系统上,打开辅助功能后,在抖音上可以每隔5秒,再向滑
动一个视频,其他系统版本没有测试过,在魅族16X上面测试没有反应,辅助功能打开后也没点日志