如何下载。来自谷歌驱动器的txt或.pdf文件,使用意图选择器选取

时间:2016-11-28 13:50:49

标签: android pdf drive

我想从驱动器下载文本和pdf文件并将其保存在设备中。 我尝试了大量的链接,但无法找到正确的解决方案。 我试过的代码如下所示

我尝试使用以下代码下载google驱动器文件。

 Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
 intent.addCategory(Intent.CATEGORY_OPENABLE);      
 intent.setType("application/*");
 Intent i = Intent.createChooser(intent, "Choose an application");
 startActivityForResult(i, RC_FILE);
onActivityResult

中的

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
    if (requestCode == RC_PICK_A_FILE) {

    Uri inputStreamUri = data.getData();
      String filePath = FilePickUtils.getPath(
                        getApplicationContext(), inputStreamUri);
    }
    }
    }

和FilePickutils

public class FilePickUtils {

@SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {

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

    // DocumentProvider
    if (isKitKatorUp && 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);
        }else if(isGoogleFileUri(uri))
        {
            Log.d("tag","====isGoogleFileUri========="+uri);
            return getDataColumn(context, uri, null, null);
        }
    }

    // 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();
    }

    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,new String[] { android.provider.MediaStore.Files.FileColumns.DATA },
                null, null, null);
        Log.d("tag","=====cursor===="+cursor);

        /* Cursor cursor = this.getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
filePath = cursor.getString(0);
cursor.close();*/
        if (cursor != null && cursor.moveToFirst()) {
            int idx = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA);
          //  final int index = cursor.getColumnIndexOrThrow(column);
            Log.d("tag","========index==="+idx);
            Log.d("tag","======cursor.getString(index)====="+cursor.getString(idx));
            return cursor.getString(idx);
        }
    } 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());
}

public static boolean isGoogleFileUri(Uri uri) {
    return "com.google.android.apps.docs.storage".equals(uri
            .getAuthority());
}

}

我最终未能获得以下内容uri

content://com.google.android.apps.docs.storage/document/acc%3D19%3Bdoc%3D10211

filePath返回为“null”

3 个答案:

答案 0 :(得分:2)

给定Uri,要制作本地文件副本,您:

  • 使用ContentResolveropenInputStream()获取InputStream

  • 所代表内容的Uri
  • 在所需文件

  • 上创建FileOutputStream
  • 使用标准Java I / O将字节从InputStream复制到FileOutputStream

你最终得到这样的代码:

    FileOutputStream fos=new FileOutputStream(f);
    BufferedOutputStream out=new BufferedOutputStream(fos);
    InputStream in=
      getContentResolver().openInputStream(document);

    try {
      byte[] buffer=new byte[8192];
      int len=0;

      while ((len=in.read(buffer))>=0) {
        out.write(buffer, 0, len);
      }

      out.flush();
    }
    finally {
      fos.getFD().sync();
      out.close();
      in.close();
    }

(其中documentUrif是目的地File

答案 1 :(得分:0)

  Uri uri = data.getData();

直接使用uri打开一个InputStream来读取它。废除那些filepicker工具。你不需要文件路径。

 InputStream is = getContentResolver().openInputStream(uri);

这就是全部。

答案 2 :(得分:-1)

解决方案:

@Override
    @SuppressLint("NewApi")
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {


             Uri mUri = CropImage.getPickImageResultUri(this, data);

             writeStreamToFile(getApplicationContext(),mUri,".pdf");

            }
        }
    }

方法:

 @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    void writeStreamToFile(Context mContext, Uri mUri,String ext) {
        if (mUri == null) {
            return;
        }

        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = mContext.getContentResolver().query(mUri, filePathColumn, null, null, null);
        String mCurrentPath = null;
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            mCurrentPath = cursor.getString(columnIndex);
            cursor.close();
        }

        if (TextUtils.isEmpty(mCurrentPath)) {
            mCurrentPath = mUri.getPath();
        }

        File storageDir = mContext.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
        InputStream inputStream = null;
        try {
            inputStream = mContext.getContentResolver().openInputStream(mUri);

            File file = File.createTempFile("pptFiles", ext, storageDir);

            try (OutputStream output = new FileOutputStream(file)) {
                byte[] buffer = new byte[4 * 1024]; // or other buffer size
                int read;
                while ((read = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, read);
                }
                output.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }