我想在我的辅助功能服务中长按“返回”按钮。我使用下面的代码。不幸的是,出了一些问题,因为我在isLongPress = false
处获得了日志。我的问题是如何正确捕获KeyEvent。
这是我的服务
package com.example.android.globalactionbarservice;
import android.accessibilityservice.AccessibilityService;
import android.util.Log;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityEvent;
import android.widget.FrameLayout;
import static android.content.ContentValues.TAG;
public class GlobalActionBarService extends AccessibilityService {
FrameLayout mLayout;
@Override
protected void onServiceConnected() {
Log.d(TAG, "MyAccessibilityService: onServiceConnected");
}
private long holdTime;
@Override
protected boolean onKeyEvent(KeyEvent event) {
Log.d(TAG, "MyAccessibilityService: onKeyEvent: action = " + event.getAction() +
"; key code = " + event.getKeyCode() +
"; scan code = " + event.getScanCode() +
"; meta state = " + event.getMetaState() +
"; key = " + event.getNumber() +
"; isLongPress = " + event.isLongPress());
return super.onKeyEvent(event);
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
Log.d(TAG, "MyAccessibilityService: onAccessibilityEvent " + event.toString());
}
@Override
public void onInterrupt() {
}
}
这是服务xml:
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagDefault|flagRequestFilterKeyEvents"
android:canRetrieveWindowContent="true"
android:canRequestFilterKeyEvents="true"
android:accessibilityEventTypes="typeContextClicked|typeViewClicked"
/>
这是我的日志:
2019-09-09 22:02:28.690 11201-11201/com.example.android.demoservice D/ContentValues: MyAccessibilityService: onServiceConnected
2019-09-09 22:02:34.109 11201-11201/com.example.android.demoservice D/ContentValues: MyAccessibilityService: onKeyEvent: action = 0; key code = 4; scan code = 158; meta state = 0; key = ��; isLongPress = false
2019-09-09 22:02:36.345 11201-11201/com.example.android.demoservice D/ContentValues: MyAccessibilityService: onKeyEvent: action = 1; key code = 4; scan code = 158; meta state = 0; key = ��; isLongPress = false
2019-09-09 22:02:47.433 11201-11201/com.example.android.demoservice D/ContentValues: MyAccessibilityService: onAccessibilityEvent EventType: TYPE_VIEW_CLICKED; EventTime: 84040825; PackageName: com.android.settings; MovementGranularity: 0; Action: 0 [ ClassName: android.widget.Button; Text: [OK]; ContentDescription: null; ItemCount: -1; CurrentItemIndex: -1; IsEnabled: true; IsPassword: false; IsChecked: false; IsFullScreen: false; Scrollable: false; BeforeText: null; FromIndex: -1; ToIndex: -1; ScrollX: -1; ScrollY: -1; MaxScrollX: -1; MaxScrollY: -1; AddedCount: -1; RemovedCount: -1; ParcelableData: null ]; recordCount: 0
谢谢。