# 一。使用 AccessibilityService 实现按钮监听,在资源文件夹新建 xml 资源文件夹,然后新 accessibility_service_config.xml。
1
2
3
4
5
6
7
8
9
10
<?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="flagRequestFilterKeyEvents"
android:canRetrieveWindowContent="true"
android:canRequestFilterKeyEvents="true"
android:description="@string/accessibility_service_description"
/>

# 二。在配置文件中配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<service
android:name=".service.MyAccessibilityService"
android:label="按钮监听"
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>


# 三。创建 MyAccessibilityService 类,继承 AccessibilityService 类 重写 onKeyEvent 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class MyAccessibilityService extends AccessibilityService {
private static final String TAG = "测试";
long aLong = 0, bLong = 0;
@Override
protected void onServiceConnected() {
super.onServiceConnected();
}



@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
}

@Override
protected boolean onKeyEvent(KeyEvent event) {
if (event.getKeyCode()==93){
bLong = System.currentTimeMillis();
if (event.getKeyCode() == 93) {
if (aLong == 0) {
aLong = System.currentTimeMillis();
} else {
if (bLong - aLong < 2000) {
Map<String, String> map = new HashMap<>();
map.put("class", "AdPresentation.class");
EventBus.getDefault().post(map);
} else {
aLong = System.currentTimeMillis();
}
}
}
}
return false;
}

@Override
public void onInterrupt() {
}
@Override
public void onDestroy() {
super.onDestroy();
}
}