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

问题描述 投票:2回答:2

我想要视频路径的实际路径,我可以使用它,我正在使用以下代码。

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和特别是三星设备。

android android-intent document
2个回答
0
投票

尝试使用

String path = yourAndroidURI.uri.getPath() // "/mnt/sdcard/FileName.mp3"
File file = new File(new URI(path));

要么

String path = yourAndroidURI.uri.toString() // "file:///mnt/sdcard/FileName.mp3"
File file = new File(new URI(path));

0
投票

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

/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帮了我很多忙。

© www.soinside.com 2019 - 2024. All rights reserved.