使用AccessibilityService模拟点击事件失败的分析

时间:2023-03-09 15:05:14
使用AccessibilityService模拟点击事件失败的分析

使用AccessibilityService模拟点击事件的方法:

AccessibilityNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);

但是前提是这个AccessibilityNodeInfo具有Onclick能力,也就是isClickable()为true。

问题在于控件的点击效果不一定非得通过onClick方法实现,也可以通过onTouchEvent方法实现。当通过onTouchEvent方法实现的时候,就无法通过AccessibilityNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK)方法模拟这个控件的点击事件了。

一、点击效果通过onClick方法实现

id_btn_openFloatWindow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.i("onClick", "onClick");
}
});

二、点击效果通过onTouchEvent方法实现

id_btn_openFloatWindow.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
onTouchEvent(event,v);
return true;//改为true,则不会触发OnClick方法
}
});
private boolean onTouchEvent(MotionEvent event, View view) {

        switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("onTouchEvent", "ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP:
Log.i("onTouchEvent", "ACTION_UP");
break;
}
return true;
}

如果采用OnTouchEvent方法实现点击事件并且没有做到和辅助功能兼容,那么也就无法通过onTouchEvent模拟该控件的点击事件了。

===================================================================

onTouchEvent方法实现与辅助性服务保持兼容性的解决方案:

自定义视图控件可能需要非标准的触摸事件的行为。例如,一个自定义控件可以使用onTouchEvent(MotionEvent)来侦测ACTION_DOWN 和 ACTION_UP事件,触发特殊的单击事件。为了与辅助性服务保持兼容性,代码处理该自定义点击事件必须做到以下几点:
  • 生成一个接近解释AccessibilityEvent的点击动作。
  • 对不能使用触摸屏的用户提供自定义点击动作的辅助性服务。
    为了用一个有效的方法来处理这些需求,代码应该重写performClick()方法,该方法必须调用超类方法的实现,然后执行任何需要通过点击事件完成的操作。当检测到自定义点击击动作,代码应该调用你的performClick()方法。下面的代码示例演示了这种模式。
class CustomTouchView extends View {

    public CustomTouchView(Context context) {
super(context);
} boolean mDownTouch = false; @Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event); // Listening for the down and up touch events
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownTouch = true;
return true; case MotionEvent.ACTION_UP:
if (mDownTouch) {
mDownTouch = false;
performClick(); // Call this method to handle the response, and
// thereby enable accessibility services to
// perform this action for a user who cannot
// click the touchscreen.
return true;
}
}
return false; // Return false for other touch events
} @Override
public boolean performClick() {
// Calls the super implementation, which generates an AccessibilityEvent
// and calls the onClick() listener on the view, if any
super.performClick(); // Handle the action for the custom click here return true;
}
}

上面所示的模式通过调用performClick()方法确保了自定义点击事件是与辅助性服务兼容的,performClick()方法既生成一个辅助性事件,又提供一个访问辅助性服务的入口,来代表用户执行了自定义的点击事件。

参考资料:

http://www.xuebuyuan.com/2061597.html