sushildlh
sushildlh

Reputation: 9056

Get File from Google drive using Intent

I am trying to upload document from my app.

Everything working fine but when i choose file from drive.

data=Intent { act=android.intent.action.VIEW dat=content://com.google.android.apps.docs.storage.legacy/enc=ckpgt5KcEEF_JYniJQafRV_5pEnu_D5UAI1WF-Lu6h2Z_Vw4
     (has extras) }}

Can any body know how to handle this file.

I had already handle all files and images only facing problem with google drive files.

I am getting this content://com.google.android.apps.docs.storage.legacy/enc=ckpgt5KcEEF_JYniJQafRV_5pEnu_D5UAI1WF-Lu6h2Z_Vw4 in intent data Uri.

Upvotes: 6

Views: 4065

Answers (2)

vikas
vikas

Reputation: 236

Handle Uri received by Google-Drive files when selected through file chooser.

as stated earlier it receives Virtual File Uri.

I found this sample code simple and easy to understand. the given code sample worked for me .hope it works in your case.

1.So detect this Uri is received by google drive.

public static File getFileFromUri(final Context context, final Uri uri) throws Exception {

if (isGoogleDrive(uri)) // check if file selected from google drive
{ 
  return saveFileIntoExternalStorageByUri(context, uri);
}else 
    // do your other calculation for the other files and return that file
   return null;
}


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

2.if yes,the uri is stored to external path(here its root directory u can change it according to your need) and the file with that uri is created.

 public static File saveFileIntoExternalStorageByUri(Context context, Uri uri) throws 

Exception {
        InputStream inputStream = context.getContentResolver().openInputStream(uri);
        int originalSize = inputStream.available();

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        String fileName = getFileName(context, uri);
        File file = makeEmptyFileIntoExternalStorageWithTitle(fileName);
        bis = new BufferedInputStream(inputStream);
        bos = new BufferedOutputStream(new FileOutputStream(
                file, false));

        byte[] buf = new byte[originalSize];
        bis.read(buf);
        do {
            bos.write(buf);
        } while (bis.read(buf) != -1);

        bos.flush();
        bos.close();
        bis.close();

        return file;

    }

public static String getFileName(Context context, Uri uri) 
{
  String result = null;
  if (uri.getScheme().equals("content")) {
  Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
  try {
       if (cursor != null && cursor.moveToFirst()) {
        result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
       }
      } finally {
                cursor.close();
            }
        }
        if (result == null) {
            result = uri.getPath();
            int cut = result.lastIndexOf('/');
            if (cut != -1) {
                result = result.substring(cut + 1);
            }
        }
        return result;
}


public static File makeEmptyFileIntoExternalStorageWithTitle(String title) {
        String root =  Environment.getExternalStorageDirectory().getAbsolutePath();
        return new File(root, title);
    }

Note:Here the virtual file is retrieved from Intent getData() and used in context.getContentResolver().openInputStream(intent.getData()), this will return an InputStream. It's handle to get selected file from google drive.

for more info go through this link

Upvotes: 15

AskNilesh
AskNilesh

Reputation: 69689

I think you are getting Virtual File Uri from google drive

Read more about Virtual Files

FROM DOCS

Virtual Files

  • Android 7.0 adds the concept of virtual files to the Storage Access Framework. The virtual files feature allows your DocumentsProvider to return document URIs that can be used with an ACTION_VIEW intent even if they don't have a direct bytecode representation. Android 7.0 also allows you to provide alternate formats for user files, virtual or otherwise

Now question is how to check the the Uri is VirtualFile or not

You can find sample code from DOCS Open virtual files

first check that Uri is VirtualFile or not

private boolean isVirtualFile(Uri uri) {
    if (!DocumentsContract.isDocumentUri(this, uri)) {
        return false;
    }

    Cursor cursor = getContentResolver().query(
        uri,
        new String[] { DocumentsContract.Document.COLUMN_FLAGS },
        null, null, null);

    int flags = 0;
    if (cursor.moveToFirst()) {
        flags = cursor.getInt(0);
    }
    cursor.close();

    return (flags & DocumentsContract.Document.FLAG_VIRTUAL_DOCUMENT) != 0;
}

The following code snippet shows how to check whether a virtual file can be represented as an image, and if so, gets an input stream from the virtual file

private InputStream getInputStreamForVirtualFile(Uri uri, String mimeTypeFilter)
    throws IOException {

    ContentResolver resolver = getContentResolver();

    String[] openableMimeTypes = resolver.getStreamTypes(uri, mimeTypeFilter);

    if (openableMimeTypes == null ||
        openableMimeTypes.length < 1) {
        throw new FileNotFoundException();
    }

    return resolver
        .openTypedAssetFileDescriptor(uri, openableMimeTypes[0], null)
        .createInputStream();
}

For more information of Virtual Files you can read below article

Upvotes: 4

Related Questions