android - 没有从android中的文档中获取所选文件的实际视频路径

标签 android android-intent document

我想要我可以使用的视频路径的实际路径,为此我使用以下代码。

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("*/*");
                    String[] mimetypes = {"video/*"};
                    intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
                    startActivityForResult(Intent.createChooser(intent, getString(R.string.select_option)), BROWSE_VIDEO_REQUEST);

onActivityResult() 获取文件后,它会给我下面的路径,比如

/document/video:27948
/document/C26B-6A27:ACTION_CREATORS_Full_HD.mp4

但我想要像 /storage/C26B-6A27/The_Basics_Full_HD.mp4

我已经尝试了其他解决方案,例如下面的链接,但没有用。

Get Real Path For Uri Android

在 API21 和特别是三星设备上面临这个问题。

最佳答案

我已经解决了所有类型的路径问题

/document/video:27948
/document/C26B-6A27:ACTION_CREATORS_Full_HD.mp4

现在我可以从 USB/SDCard/Gallery/Documents 等任何地方选择任何文件,除了 GoogleDrive 和 Dropbox 等。

使用下面的代码。

点击按钮

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("*/*");
                    String[] mimetypes = {"video/*"};
                    intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
                    startActivityForResult(intent, BROWSE_VIDEO_REQUEST);

onActivityResult()

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    switch (requestCode) {
        case BROWSE_VIDEO_REQUEST:
            if (resultCode == RESULT_OK) {
                try {
                    String PathHolder = data.getData().getPath();
                    if (FileUtil.isFileExist(PathHolder)) {  // /storage/UsbDriveA/React_Native.mp4
                        Log.e(TAG, "SWAPLOG PATH = exist");
                        if (PathHolder.endsWith(".mp4") || PathHolder.endsWith(".3gp") || PathHolder.endsWith(".avi")) {
                            //Found Real path
                            mVideoPath = PathHolder;
                            goToPlayVideo();
                        } else {
                            Utility.showToast(SelectVideoActivity.this, getString(R.string.select_any_video_file), Toast.LENGTH_SHORT);
                        }
                    } else {  // /document/video:27948
                        FromSDCard(data.getData());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Utility.showToast(SelectVideoActivity.this, getString(R.string.video_is_not_available), Toast.LENGTH_SHORT);
                }
            }
            break;
    }
}

/**
 * get Data from SDCard
 */
private void FromSDCard(Uri uri) {
    try {
        String selectedFilePath = RealPathUtil.getPath(SelectVideoActivity.this, uri);
        if(selectedFilePath != null) {
            final File file = new File(selectedFilePath);
            if (file.exists()) {
                String filePath = file.getPath();
                if (filePath.endsWith(".mp4") || filePath.endsWith(".3gp") || filePath.endsWith(".avi")) {
                    //Found Real path
                    mVideoPath = filePath;
                    goToPlayVideo();
                } else {
                    Utility.showToast(SelectVideoActivity.this, getString(R.string.select_any_video_file), Toast.LENGTH_SHORT);
                }
            } else {
                getFromDocument(uri);
            }
        }else{
            getFromDocument(uri);
        }
    } catch (Exception e) {
        e.printStackTrace();
        getFromDocument(uri);
    }
}

/**
 * get Data from document path
 */
private void getFromDocument(Uri uri) {
    String orignalPath = uri.getPath();
    try {
        if (orignalPath.endsWith(".mp4") || orignalPath.endsWith(".3gp") || orignalPath.endsWith(".avi")) { // /document/C26B-6A27:React_Native.mp4
            String getFilePath = RealPathUtil.getDocumentPath(uri);
            if (getFilePath != null) {
                if (FileUtil.isFileExist(getFilePath)) {
                    //Found Real path
                    mVideoPath = getFilePath;
                    goToPlayVideo();
                }else{
                    Utility.showToast(SelectVideoActivity.this, getString(R.string.video_is_not_available), Toast.LENGTH_SHORT);
                }
            } else {
                Utility.showToast(SelectVideoActivity.this, getString(R.string.video_is_not_available), Toast.LENGTH_SHORT);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        Utility.showToast(SelectVideoActivity.this, getString(R.string.video_is_not_available), Toast.LENGTH_SHORT);
    }
}

还有一个 RealPathUtil.java

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import java.io.File;

public class RealPathUtil {

    /**
     * Method for return file path of Gallery image/ Document / Video / Audio
     *
     * @param context
     * @param uri
     * @return path of the selected image file from gallery
     */
    public static String getPath(final Context context, final Uri uri) {

        try {
            // check here to KITKAT or new version
            final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

            // DocumentProvider
            if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

                // ExternalStorageProvider
                if (isExternalStorageDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    if ("primary".equalsIgnoreCase(type)) {
                        return Environment.getExternalStorageDirectory() + "/"
                                + split[1];
                    }
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri)) {

                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"),
                            Long.valueOf(id));

                    return getDataColumn(context, contentUri, null, null);
                }
                // MediaProvider
                else if (isMediaDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }

                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[]{split[1]};

                    return getDataColumn(context, contentUri, selection,
                            selectionArgs);
                }
            }
            // MediaStore (and general)
            else if ("content".equalsIgnoreCase(uri.getScheme())) {

                // Return the remote address
                if (isGooglePhotosUri(uri))
                    return uri.getLastPathSegment();

                return getDataColumn(context, uri, null, null);
            }
            // File
            else if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri,
                                       String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection,
                    selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri
                .getAuthority());
    }

    /**
     * Method for return file path of USB image/ Document / Video / Audio
     *
     * @param uri
     * @return path of the selected image file from gallery
     */
    public static String getDocumentPath(final Uri uri) {
        try {
            String selectedFilePath = uri.getPath();
                if (selectedFilePath.contains("/document/")) {
                    selectedFilePath = selectedFilePath.replace("/document/", "/storage/");
                }
                if (selectedFilePath.contains(":")) {
                    selectedFilePath = selectedFilePath.replace(":", "/");
                }
                final File file = new File(selectedFilePath);
                if (file.exists()) {
                    String FilePath = file.getPath();
                    if (FilePath.endsWith(".mp4") || FilePath.endsWith(".3gp") || FilePath.endsWith(".avi")) {
                        return FilePath;
                    }
                }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

注意:

Creating file from Uri对我帮助很大。

关于android - 没有从android中的文档中获取所选文件的实际视频路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55466857/

相关文章:

java - 打开通知设置页面 android oreo

android - 更新 Android SDK 工具和 ADT 后调试 UI : java. lang.reflect.InvocationTargetException 中的错误

java - 两个通知之间的 onHandleIntent 中隐含的 Intent 不同

android - 无法使用 4.2.2 AVD 上的 Intent 选择器从相机获取图像

node.js - MongoDB 创建文档并成功创建另一个文档

version-control - 如何使用 Mercurial 进行文本文档的版本控制?

jquery - 如何将 .ajax() responseText 设置为变量

android - 以编程方式暂停媒体记录器。来自三星银河的 Camera.apk 有 `this.mMediaRecorder.pause();` 在我的代码中不起作用

Android Fragment - 从一个 View 移动到另一个 View ?

android - 切换 Intent 时我丢失了数据