AccessibilityService首先你要继承AccessibilityService,你会被要求复写
onKeyEvent、onIntercept、onAccessibilityEvent等方法。我们看这些方法在AccessibilityService中是如何实现的。
public class AccessBackKeyService extends AccessibilityService {
private static final String TAG = "jason";
@Override
protected boolean onKeyEvent(KeyEvent event) {
Log.i(TAG, "onKeyEvent");
if(event.getAction() == KeyEvent.ACTION_DOWN){
return super.onKeyEvent(event);
}
Log.i(TAG, "onKeyEvent ACTION_DOWN");
int key = event.getKeyCode();
switch(key){
case KeyEvent.KEYCODE_VOLUME_DOWN:
Log.i(TAG, "KEYCODE_VOLUME_DOWN");
break;
case KeyEvent.KEYCODE_VOLUME_UP:
Log.i(TAG, "KEYCODE_VOLUME_UP");
Toast.makeText(this, "KEYCODE_VOLUME_UP", Toast.LENGTH_SHORT).show();
break;
case KeyEvent.KEYCODE_BACK:
Log.i(TAG, "KEYCODE_BACK");
Toast.makeText(this, "KEYCODE_BACK, source:"+event.getSource(), Toast.LENGTH_SHORT).show();
break;
case KeyEvent.KEYCODE_ESCAPE:
Log.i(TAG, "KEYCODE_ESCAPE");
Toast.makeText(this, "KEYCODE_ESCAPE", Toast.LENGTH_SHORT).show();
break;
}
return super.onKeyEvent(event);
}
@Override
public void onInterrupt() {
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
// TODO Auto-generated method stub
}
@Override
protected boolean onGesture(int gestureId) {
Log.i("jason", "onGesture:"+gestureId);
return super.onGesture(gestureId);
}
}
我们看到AccessibilityService中有一个接口
/**
* @hide
*/
public interface Callbacks {
public void onAccessibilityEvent(AccessibilityEvent event);
public void onInterrupt();
public void onServiceConnected();
public void init(int connectionId, IBinder windowToken);
public boolean onGesture(int gestureId);
public boolean onKeyEvent(KeyEvent event);
public void onMagnificationChanged(@NonNull Region region,
float scale, float centerX, float centerY);
public void onSoftKeyboardShowModeChanged(int showMode);
public void onPerformGestureResult(int sequence, boolean completedSuccessfully);
}
AccessibilityService利用观察者模式的形式将自己封装进一个IAccessibilityServiceClientWrapper内部类中,在onBind方法中实现,猜测在辅助功能打开开关的时候,onBind这个方法将被调用,一会我们从源码分析,先分析一下
IAccessibilityServiceClientWrapper
。