从其他应用程序获取文件的路径

Get the path of a file from other app

在我的应用程序中,我处理来自其他应用程序的 images/videos 共享。

问题是,如果我想处理图库中的图像,它在以下情况下效果很好:

    Uri fileUri = (Uri) data.getParcelableExtra(Intent.EXTRA_STREAM);


    String[] projection = {MediaStore.MediaColumns.DATA};
    CursorLoader cursorLoader = new CursorLoader(mChatView.returnContext(), fileUri, projection, null, null, null);
    Cursor cursor = cursorLoader.loadInBackground();
    cursor.moveToFirst();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    File selectedImage = new File(cursor.getString(column_index));

我正在获取我想要的文件。

问题是图像是通过其他应用程序共享的(Whatsapp/Fb Messenger)我得到:

cursor == null

Whatsapp 示例 URI

fileUri = file:///storage/emulated/0/WhatsApp/Media/WhatsApp%20Images/Sent/IMG-20160616-WA0000.jpg

如何访问该文件?

-在 Nexus 5 上测试 - Android v 6.0.1

这样做:

    String uri = data.getParcelableExtra(Intent.EXTRA_STREAM).toString();

    Uri fileUri = (Uri) data.getParcelableExtra(Intent.EXTRA_STREAM);

    File selectedImage;

    if (uri.startsWith("file://")) {
        selectedImage = new File(fileUri.getPath());
    } 
    else 
    {
        String[] projection = {MediaStore.MediaColumns.DATA};
        CursorLoader cursorLoader = new CursorLoader(mChatView.returnContext(), fileUri, projection, null, null, null);
        Cursor cursor = cursorLoader.loadInBackground();
        cursor.moveToFirst();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
        selectedImage = new File(cursor.getString(column_index));
    }