如何获取Google驱动器文档的文件名和实际路径?

Suc*_*chi 12 android google-drive-api

我使用以下代码来获取文件管理器中的文件名和文件路径.但是,它不会返回Google云端硬盘文件的路径.知道如何获得实际路径吗?

我的代码 -

public String getFilePath() {
    if (uri.getScheme().equalsIgnoreCase("file")) {
        return uri.getLastPathSegment();
    }

    cursorLoader.setUri(uri);
    cursorLoader.setProjection(projections);
    Cursor cursor = cursorLoader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA);
    cursor.moveToFirst();
    String realPath = cursor.getString(column_index);
    cursor.close();

    if (realPath == null || realPath.isEmpty()) {
        return null;
    }

return null;
}
Run Code Online (Sandbox Code Playgroud)

clo*_*erk 10

您必须使用URI.通过URI,你可以getContentResolver.query(theUriThatYouHave, null, null, null, null).现在你有了一个游标,你可以检查列名等.

对于Google云端硬盘,有一个列名称_display_name.这将为您提供文件名.

现在您想要访问该文件?您可以通过打开InputStreamURI getContentResolver().openInputStream(theUriThatYouHave).

  • 您能否提供完整的示例,说明如何从该路径中准确获取文件? (4认同)

sat*_*are 6

通过以下步骤可以轻松从 Google Drive URI 获取文件名和真实路径:

  1. 在 Android 清单文件中添加文件提供程序路径。

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.demo.filemangerdemo">
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.STORAGE" />
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name="com.demo.filemangerdemo.activity.MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <provider
                android:name="android.support.v4.content.FileProvider"
                android:authorities="${applicationId}.provider"
                android:exported="false"
                android:grantUriPermissions="true">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/provider_paths"/>
            </provider>
        </application>
    </manifest>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在res下创建xml文件夹并添加provider_paths.xml。

    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
        <cache-path
            name="my_cache"
            path="." />
        <cache-path
            name="cache"
            path="." />
        <external-cache-path
            name="external_cache"
            path="." />
        <files-path
            name="files"
            path="." />
    </paths>
    
    Run Code Online (Sandbox Code Playgroud)
  3. 用于从 Google Drive 访问数据的 Utils 类。

    public class Utils {
        private static Uri contentUri = null;
    
        @SuppressLint("NewApi")
        public static String getPath(final Context context, final Uri uri) {
            // 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))
              {
                // MediaProvider
                 if (isMediaDocument(uri)) {
                     if (isGoogleDriveUri(uri)) {
                    return getDriveFilePath(uri, context);
                }
    
    
              }
          }
    
    Run Code Online (Sandbox Code Playgroud)
  4. isGoogleDriveUri 方法

    private static boolean isGoogleDriveUri(Uri uri) {
        return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
    }
    
    Run Code Online (Sandbox Code Playgroud)
  5. 获取驱动器文件路径方法

    private static String getDriveFilePath(Uri uri, Context context) {
        Uri returnUri = uri;
        Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
        /*
         * Get the column indexes of the data in the Cursor,
         *     * move to the first row in the Cursor, get the data,
         *     * and display it.
         * */
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
        returnCursor.moveToFirst();
    
        String name = (returnCursor.getString(nameIndex));
        String size = (Long.toString(returnCursor.getLong(sizeIndex)));
        File file = new File(context.getCacheDir(), name);
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            FileOutputStream outputStream = new FileOutputStream(file);
            int read = 0;
            int maxBufferSize = 1 * 1024 * 1024;
            int bytesAvailable = inputStream.available();
    
            //int bufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);
    
            final byte[] buffers = new byte[bufferSize];
            while ((read = inputStream.read(buffers)) != -1) {
                outputStream.write(buffers, 0, read);
            }
            Log.e("File Size", "Size " + file.length());
            inputStream.close();
            outputStream.close();
            Log.e("File Path", "Path " + file.getPath());
        } catch (Exception e) {
            Log.e("Exception", e.getMessage());
        }
            return file.getPath();
        }     
    }
    
    Run Code Online (Sandbox Code Playgroud)
  6. 在onActivityResult中获取文件路径

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            if ((data != null) && (data.getData() != null)) {
                Uri selectedFile = data.getData();
                if (selectedFile.getLastPathSegment() != null) {
                    //Here you will get File Path
                    String strPath = FileUtils.getPath(this, selectedFile);  
                }
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)