Android copy/paste from clipboard manager

前端 未结 7 1053
情书的邮戳
情书的邮戳 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:33

    For most Android devices, above Honeycomb Android version 3.0 the below code will work

    For copying text to Clipboard

    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
            ClipData clip = android.content.ClipData
                        .newPlainText("copyingToClipboard", "your text here to be copied to clipboard");
        clipboard.setPrimaryClip(clip);
    

    For Copying from Clipboard

    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            if (clipboard.hasPrimaryClip() && (clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN) || clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_HTML))) {
                ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
                String clipboardtext = item.getText().toString();
                Toast.makeText(Context,clipboardtext,Toast.LENGTH_LONG).show();
            }
    

    The code will avoid null value exception in case the clipboard doesn't contain any data.

提交回复
热议问题