Android copy/paste from clipboard manager

前端 未结 7 1039
情书的邮戳
情书的邮戳 2020-11-28 10:04

Is it possible to send past command so that it pastes text into currently focused edit text. Scenario:

  1. Background service listening for notification (done)
7条回答
  •  执念已碎
    2020-11-28 10:34

    If you just want to "copy and paste" some code into your app, you can use the following.

    #Copy

    String textToCopy = etCodeWindow.getText().toString();
    
    ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    ClipData clip = ClipData.newPlainText(null, textToCopy);
    if (clipboard == null) return;
    clipboard.setPrimaryClip(clip);
    

    #Paste

    Get the text to paste

    ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    if (clipboard == null) return;
    ClipData clip = clipboard.getPrimaryClip();
    if (clip == null) return;
    ClipData.Item item = clip.getItemAt(0);
    if (item == null) return;
    CharSequence textToPaste = item.getText();
    if (textToPaste == null) return;
    

    or

    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    try {
        CharSequence textToPaste = clipboard.getPrimaryClip().getItemAt(0).getText();
    } catch (Exception e) {
        return;
    }
    

    or the same in Kotlin:

    val clipboard = (getSystemService(Context.CLIPBOARD_SERVICE)) as? ClipboardManager
    val textToPaste = clipboard?.primaryClip?.getItemAt(0)?.text ?: return false
    

    Inserting it at the cursor position

    If there is a selection then the selection will be replaced with the paste text.

    int start = Math.max(myEditText.getSelectionStart(), 0);
    int end = Math.max(myEditText.getSelectionEnd(), 0);
    myEditText.getText().replace(Math.min(start, end), Math.max(start, end),
                textToPaste, 0, textToPaste.length());
    

    #Notes

    • This answer assumes that you are no longer supporting pre-API 11. If you are then see the edit history.
    • Import android.content.ClipboardManager and android.content.ClipData.
    • I used to just get the paste text in a one liner until I discovered that ClipData was giving a NPE crash sometimes. Now I would either use a try/catch block or check more carefully for nulls.

提交回复
热议问题