复制/粘贴URI MIME类型始终为空

时间:2014-09-06 12:30:22

标签: android copy uri mime-types paste

我正在尝试在我的应用中实现复制/粘贴功能。我一直关注Android Developer上的Copy and Paste部分,但我想我做错了,因为它不起作用。问题是,在粘贴时,uriMimeType始终为空,我不明白Uri MIME类型是如何工作的。请注意,pasteUri指向与copyUri完全相同的文件。我的代码如下:

private static void copy() {
    ...
    Uri copyUri = Uri.parse(file.getAbsolutePath());
    ClipData clip = ClipData.newUri(getContentResolver(), "My URI", copyUri);
    clipboard.setPrimaryClip(clip);
}

private static void paste() {
    ClipboardManager clipBoard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    ContentResolver contentResolver = getContentResolver();

    if (!(clipBoard.hasPrimaryClip())) return; // The clipboard has no data
    if (!(clipBoard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN))) {
        // The clipboard has data, but it is not plain text. We will now proceed to check if it is an URI.
        ClipData clip = clipBoard.getPrimaryClip();
        if (clip != null) {
            ClipData.Item item = clip.getItemAt(0);
            // Try to get the item's contents as a URI
            Uri pasteUri = item.getUri();
            if (pasteUri != null) {
                // Check if it is a content URI
                String uriMimeType = contentResolver.getType(pasteUri);
                // If the return value is not null, the URI is a content URI
                if (uriMimeType != null) {
                    // uriMimeType is always null!
                    ...
                }
            }
        }
    } else {
        // The clipboard has data and it is plain text
        ClipData.Item item = clipBoard.getPrimaryClip().getItemAt(0);
        String pasteData = (String) item.getText().toString();

        if (pasteData != null) {
            // Do some stuff
            return;
        }
    }
}

0 个答案:

没有答案