1. AccessibilityService的介绍
前几天在浏览技术博客时,看到一篇文章自动抢红包,自动安装原理之AccessibilityService。发现了Android提供了一个很有趣的辅助类——AccessibilityService!决定自己也来探索一番。
先来看看AccessibilityService官方的介绍:
Accessibility services are intended to assist users with disabilities in using Android devices and apps. They run in the background and receive callbacks by the system whenAccessibilityEvents are fired. Such events denote some state transition in the user interface, for example, the focus has changed, a button has been clicked, etc. Such a service can optionally request the capability for querying the content of the active window. Development of an accessibility service requires extending this class and implementing its abstract methods.
英语不好,就不献丑了,大概意思是AccessibilityServices能辅助用户使用Android设备和app,其运行在后台并会监听系统诸如窗体改变、按钮点击等AccessibilityEvent事件,然后我们就能根据这些事件来完成一些操作了。也就是说,AccessibilityService能释放我们的双手,辅助我们完成一些我们平常主动地操作手机的动作。我的理解是,主要我们愿意并且不怕麻烦,几乎能用AccessibilityService使我们的手机完成自动化。
2. AccessibilityService的创建和配置:
先创建于继承与AccessibilityService的类:
public class MyAccessibilityService extends AccessibilityService{
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
}
@Override
public void onInterrupt() {
}
}
AccessibilityService是继承于Service的,所以需要在AndroidMainfest.xml里声明:
<service
android:name="com.leo.service.MyAccessibilityService"
android:enabled="true"
android:exported="true"
android:label="@string/MyAccessibilityService"
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/my_service_config" />
</service>
细心的朋友应该注意到了,要为AccessibilityService指定好配置文件res/xml/my_service_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeAllMask" // 指定接收事件类型,typeAllMask代表全部都接收
android:accessibilityFeedbackType="feedbackGeneric" // 反馈方式
android:canRetrieveWindowContent="true" // 是否能获取活动窗口内容,这个很重要哦
android:description="@string/auto_reply_description" // 对服务的描述
android:notificationTimeout="100" // 响应事件的间隔,单位为毫秒
android:packageNames="com.tencent.mm" /> // 指定监听的应用程序的包名,这里我指定了微信的包名
也可以重写onServiceConnected()在代码里配置:
@Override
protected void onServiceConnected() {
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
info.packageNames = new String[]{Config.WX_PACKAGE_NAME};
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN;
info.notificationTimeout = 100;
this.setServiceInfo(info);
}
最后加上权限:
<uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"/>
然后我们把程序安装到手机-->设置-->辅助功能-->开启服务。到这里我们已经完成AccessibilityService的配置了。当然它还不能做任何事,因为我们只是配置好,并没有做任何操作。了解了AccessibilityService后,接下来就可以进入主题了: