Search code examples
androidaccessibilityservice

Insert or erase character on field without erase previous content


There some function in AcessibilityService where can insert character on field, but without erase previous content as well simulate backspace button?

by now i'm make it with a global String variable eg:

  • text += "My text or character here - Insertion
  • text = text.substring(0, text.length() - 1) - Backspace

This isn't good because when jump to next field is necessary clear the variable before.


Solution

  • Here is a how could be a implementation after suggestion presented by @Pawan Singh Harariya.

    PS: Tested in Youtube and Google Chrome.

    public void keyboardText(String text) {
        Bundle arguments = new Bundle();
        AccessibilityNodeInfo node = findFocus(AccessibilityNodeInfo.FOCUS_INPUT);
    
        if (node != null) {
            String nodeHint = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                nodeHint = String.valueOf(node.getHintText());
            }
    
            String nodeText = String.valueOf(node.getText());
    
            if (nodeHint != null) {
                if (text.equals("BACKSPACE"))
                    nodeText = nodeText.substring(0, nodeText.length() - 1).replace(nodeHint, "");
                else if (text.equals("SPACE"))
                    nodeText = nodeText.replace(nodeHint, "") + " ";
                else nodeText = nodeText.replace(nodeHint, "") + text;
            } else {
                if (text.equals("BACKSPACE"))
                    nodeText = nodeText.substring(0, nodeText.length() - 1);
                else if (text.equals("SPACE"))
                    nodeText += " ";
                else nodeText += text;
            }
    
            arguments.putString(AccessibilityNodeInfoCompat.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, nodeText);
            node.performAction(AccessibilityNodeInfoCompat.ACTION_SET_TEXT, arguments);
        }
    }