Making local copy of file using Google Drive API - android

I want to make local copy(external storage) of a '.ppt' file present on Google Drive using Google Drive android Api.
I am reading one byte and writing it to my local file. But when I am trying to open it shows that file is corrupt. Please help me to resolve my problem.
final DriveFile file = Drive.DriveApi.getFile(getClient(), fileid);
final Metadata[] metadata = new Metadata[1];
file.getMetadata(getClient())
.setResultCallback(new ResultCallback<DriveResource.MetadataResult>() {
#Override
public void onResult(DriveResource.MetadataResult metadataResult) {
metadata[0] = metadataResult.getMetadata();
L.b(EditorWindow.this, metadata[0].getMimeType(), 0);
}
});
file.open(getClient(), DriveFile.MODE_READ_ONLY, null)
.setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
L.c("Error in creating new file");
return;
}
DriveContents contents = result.getDriveContents();
String filename = metadata[0].getTitle();
File localFile = new File(Environment.getExternalStorageDirectory(), filename);
OutputStream out = null;
InputStream in = null;
try {
out = new BufferedOutputStream(new FileOutputStream(localFile));
in = contents.getInputStream();
int b;
while ( (b = in.read()) > 0) {
out.write(b);
}
in.close();
out.close();
} catch (Exception e) {L.c("Error in writing to SD card");}
contents.discard(getClient());
}
});

Can you try changing your while condition to ( (b = in.read()) >= 0)? Note that 0 is a valid byte to be read from an InputStream.
http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read()

Related

How to upload all the audio files in a directory to the google drive?

I am facing the issue in uploading the list of audio to google drive.
I can upload the single audio file from a directory but i tried to upload the list of audio files is failed.
This is the path for the single audio file
final String path = new String(Environment.getExternalStorageDirectory() + "/CallLogs/Yaendi Yaendi.mp3");
How to upload the all the audio files in the CallLogs directory.
public void CreateFileOnGoogleDrive(DriveApi.DriveContentsResult result) {
final DriveContents driveContents = result.getDriveContents();
// Perform I/O off the UI thread.
new Thread() {
#Override
public void run() {
// write content to DriveContents
OutputStream outputStream = driveContents.getOutputStream();
final String path = new String(Environment.getExternalStorageDirectory() + "/CallLogs/Yaendi Yaendi.mp3");
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(path));
} catch (FileNotFoundException e) {
showErrorDialog();
e.printStackTrace();
}
byte[] buf = new byte[1024];
int bytesRead;
try {
if (inputStream != null) {
while ((bytesRead = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, bytesRead);
}
}
} catch (IOException e) {
showErrorDialog();
e.printStackTrace();
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("callLog")
.setMimeType("audio/mpeg")
.setStarred(true).build();
// create a file in root folder
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, changeSet, driveContents).setResultCallback(fileCallback);
}
}.start();
Toast.makeText(getActivity(), "Created Successfully", Toast.LENGTH_SHORT).show();
}
The above code is for uploading the single audio file to google drive.
Please help me how to upload the all the files to the google drive.
Place your code inside AsyncTask's doInBackground() method.

How to set/get the ID of the file just uploaded to Google Drive from my Android app?

I'm trying to solve this problem for a long time.
This part of code download image to GDrive.
public void UploadFileOnGoogleDrive(DriveContentsResult result){
final DriveContents driveContents=result.getDriveContents();
new Thread(){
#Override
public void run(){
OutputStream outputStream = driveContents.getOutputStream();
// Write the bitmap data from it.
String photo = "IMG23.jpg";
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),photo);
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
int numOfbytes = myBitmap.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(numOfbytes);
myBitmap.copyPixelsToBuffer(buffer);
//imageInByte = buffer.array();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
//outputStream.write(bitmapStream.toByteArray());
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg")
.setTitle(photo)
.setIndexableText(photo)
.build();
Log.d("Description",metadataChangeSet.getIndexableText());
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, metadataChangeSet, driveContents).
setResultCallback(fileCallback);
//Drive.DriveApi.fetchDriveId(mGoogleApiClient,EXISTING_FILE_ID).setResultCallback(idfileCallback);
}
}.start();
}
Here I try to get file ID
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
if (result.getStatus().isSuccess()) {
Toast.makeText(getApplicationContext(), "file created: "+""+
result.getDriveFile().getDriveId(), Toast.LENGTH_LONG).show();
//DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, result.getDriveFile().getDriveId());
//file.getMetadata(mGoogleApiClient)
// .setResultCallback(metadataRetrievedCallback);
//String id=file.getDriveId().encodeToString();
Log.d("Fileidis",result.getDriveFile().getDriveId().encodeToString());
//final DriveId fileid = result.getDriveFile().getDriveId();
//DriveFile driveFile=Drive.DriveApi.getFile(mGoogleApiClient,fileid);
}
return;
}
};
But we find not fully ID in logs
07-06 15:15:50.939 19899-19899/valery.pankov.gdriveapp D/Fileidis: DriveId:CAESABj4XSCG9Oqbt1EoAA==
I thought set idResultCallback on UploadFileOnGoogleDrive but it was not successfull.
Thanks in advance

Uploading video to Google Drive programmatically (Android API)

I have followed the Drive API guide (https://developer.android.com/google/play-services/drive.html) and my app now uploads photos smoothly, but I am now trying to upload videos (mp4) without success.
Does anyone know how to achieve this? The video is a newly generated mp4 file and I have the path to where it is stored on the device.
For pictures its done like this:
Drive.DriveApi.newDriveContents(mDriveClient).setResultCallback(
new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
OutputStream outputStream = result.getDriveContents().getOutputStream();
// Write the bitmap data from it.
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 80, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
image.recycle();
outputStream = null;
String title = Shared.getOutputMediaFile(Shared.MEDIA_TYPE_IMAGE).getName();
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg").setTitle(title)
.build();
Log.i(TAG, "Creating new pic on Drive (" + title + ")");
Drive.DriveApi.getFolder(mDriveClient,
mPicFolderDriveId).createFile(mDriveClient,
metadataChangeSet, result.getDriveContents());
}
});
}
What I am interested in is an alternative for a File, in this case pointing to a "video/mp4".
Without getting into much detail, just a few pointers:
Anything you want to upload (image, text, video,...) consists from
creating a file
setting metadata (title, MIME type, description,...)
setting content (byte stream)
The demo you mention does it with an image (JPEG bytestream) and you need to do it with video. So, the changes you need to implement are:
replace the "image/jpeg" MIME type with the one you need for your
video
copy your video stream (outputStream.write(bitmapStream.toByteArray())...)
to the content.
These are the only changes you need to make. Google Drive Android API doesn't care what is your content and metadata, it just grabs it a shoves it up to Google Drive.
In Google Drive, apps (web, android,...) read the metadata and content, and treat it accordingly.
So this my complete code how I achieved uploading a video.
Steps:
Fetch video file from uri(as in my case).
Get the byte array from bytearray outputstream as mentioned in the code
write the byte array to the ouputStream
the api will upload the file in the background
public class UploadVideo extends AppCompatActivity {
DriveClient mDriveClient;
DriveResourceClient mDriveResourceClient;
GoogleSignInAccount googleSignInAccount;
String TAG = "Drive";
private final int REQUEST_CODE_CREATOR = 2013;
Task<DriveContents> createContentsTask;
String uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_video);
//Fetching uri or path from previous activity.
uri = getIntent().getStringExtra("uriVideo");
//Get previously signed in account.
googleSignInAccount = GoogleSignIn.getLastSignedInAccount(this);
if (googleSignInAccount != null) {
mDriveClient = Drive.getDriveClient(getApplicationContext(), googleSignInAccount);
mDriveResourceClient =
Drive.getDriveResourceClient(getApplicationContext(), googleSignInAccount);
}
else Toast.makeText(this, "Login again and retry", Toast.LENGTH_SHORT).show();
createContentsTask = mDriveResourceClient.createContents();
findViewById(R.id.uploadVideo).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createFile();
}
});
}
private void createFile() {
// [START create_file]
final Task<DriveFolder> rootFolderTask = mDriveResourceClient.getRootFolder();
final Task<DriveContents> createContentsTask = mDriveResourceClient.createContents();
Tasks.whenAll(rootFolderTask, createContentsTask)
.continueWithTask(new Continuation<Void, Task<DriveFile>>() {
#Override
public Task<DriveFile> then(#NonNull Task<Void> task) throws Exception {
DriveFolder parent = rootFolderTask.getResult();
DriveContents contents = createContentsTask.getResult();
File file = new File(uri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
FileInputStream fis = new FileInputStream(file);
for (int readNum; (readNum = fis.read(buf)) != -1;) {
baos.write(buf, 0, readNum);
}
OutputStream outputStream = contents.getOutputStream();
outputStream.write(baos.toByteArray());
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("MyVideo.mp4") // Provide you video name here
.setMimeType("video/mp4") // Provide you video type here
.build();
return mDriveResourceClient.createFile(parent, changeSet, contents);
}
})
.addOnSuccessListener(this,
new OnSuccessListener<DriveFile>() {
#Override
public void onSuccess(DriveFile driveFile) {
Toast.makeText(Upload.this, "Upload Started", Toast.LENGTH_SHORT).show();
finish();
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "Unable to create file", e);
finish();
}
});
// [END create_file]
}
}
If you want to upload any file to Google Drive, then use the below code with Synchronization task, it will upload your file to Drive.
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>()
{
#Override
protected String doInBackground(Void... params)
{
String file_type="video/mp4"; //write your file type
File body = new File();
File FileRtr = null;
body.setTitle(myfile.getName());
body.setMimeType(file_type);
body.setParents(Arrays.asList(new ParentReference().setId(LocationID))); //LocationID means the path in the drive e where you want to upload it
try
{
FileContent mediaContent = new FileContent(file_type, myfile);
FileRtr = mService.files().insert(body, mediaContent).execute();
if ( FileRtr != null)
{
System.out.println("File uploaded: " + FileRtr.getTitle());
}
}
catch (IOException e)
{
System.out.println("An error occurred: " + e.getMessage());
}
return null;
}
protected void onPostExecute(String token)
{
Toast.makeText(mContext, "Uploaded Successfuly",Toast.LENGTH_LONG).show();
}
};
task.execute();
Solution by OP.
Thanks to seanpj, turns out I was overestimating the difficulty of this, I now use this method to upload both images and videos:
/**
* Create a new file and save it to Drive.
*/
private void saveFiletoDrive(final File file, final String mime) {
// Start by creating a new contents, and setting a callback.
Drive.DriveApi.newDriveContents(mDriveClient).setResultCallback(
new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
// If the operation was not successful, we cannot do
// anything
// and must
// fail.
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
Log.i(TAG, "Connection successful, creating new contents...");
// Otherwise, we can write our data to the new contents.
// Get an output stream for the contents.
OutputStream outputStream = result.getDriveContents()
.getOutputStream();
FileInputStream fis;
try {
fis = new FileInputStream(file.getPath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
byte[] photoBytes = baos.toByteArray();
outputStream.write(photoBytes);
outputStream.close();
outputStream = null;
fis.close();
fis = null;
} catch (FileNotFoundException e) {
Log.w(TAG, "FileNotFoundException: " + e.getMessage());
} catch (IOException e1) {
Log.w(TAG, "Unable to write file contents." + e1.getMessage());
}
String title = file.getName();
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType(mime).setTitle(title).build();
if (mime.equals(MIME_PHOTO)) {
if (VERBOSE)
Log.i(TAG, "Creating new photo on Drive (" + title
+ ")");
Drive.DriveApi.getFolder(mDriveClient,
mPicFolderDriveId).createFile(mDriveClient,
metadataChangeSet,
result.getDriveContents());
} else if (mime.equals(MIME_VIDEO)) {
Log.i(TAG, "Creating new video on Drive (" + title
+ ")");
Drive.DriveApi.getFolder(mDriveClient,
mVidFolderDriveId).createFile(mDriveClient,
metadataChangeSet,
result.getDriveContents());
}
if (file.delete()) {
if (VERBOSE)
Log.d(TAG, "Deleted " + file.getName() + " from sdcard");
} else {
Log.w(TAG, "Failed to delete " + file.getName() + " from sdcard");
}
}
});
}
There is one more way to upload file to Google Drive without using Drive API. Using Intent you can implement this. (Tested on Android 12)
String your_file_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath()
+ "/XYZ/Database/"+FILE_NAME+"_");
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("*/*");
Uri photoURI = FileProvider.getUriForFile(this, "authorities_from_manifest_file_of_provider_tag",new File(your_file_path));
intent.setPackage("com.google.android.apps.docs"); //Google Drive
intent.putExtra(Intent.EXTRA_STREAM,photoURI);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intent, "Save Backup"));
You must have added working File Provider in your Manifest before implementing of this.
Note: "authorities_from_manifest_file_of_provider_tag" is the attribute value of android:authorities this from manifest. i.e -
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.your.packageName.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>

How to use AWS S3 PersistableDownload on Android SDK

Has anyone been able to use PersistableDownload on AWS Android SDK? I've been trying to use it to resume downloads when the App crashes, but with no success so far. I don't think I'm getting the concept serialize/deserialize right. Here is the code I got so far:
AmazonS3Client s3Client = getAmazonS3Client(Regions.SA_EAST_1);
TransferManager tx = new TransferManager(s3Client);
String bucket = "MyBucket";
String key = "IMG_20140915_132548.jpg";
String[] parts = key.split("/");
String fileName = parts[parts.length - 1];
final String full_path = "/storage/sdcard0/" + fileName;
File file = new File(full_path);
FileInputStream fis = null;
if(file.exists()) {
try {
fis = new FileInputStream(file);
PersistableDownload persistableUpload = PersistableTransfer.deserializeFrom(fis);
Download meuDown = tx.resumeDownload(persistableUpload);
} catch (Exception e1) {
e1.printStackTrace();
}
}
else {
GetObjectRequest getRequest = new GetObjectRequest(bucket, "IMG_20140915_132548.jpg");
Download download = tx.download(getRequest, file, new S3ProgressListener() {
#Override
public void progressChanged(ProgressEvent arg0) {
long transferred = arg0.getBytesTransferred();
Log.d("AWS3", "" + transferred);
}
#Override
public void onPersistableTransfer(PersistableTransfer arg0) {
Log.d("AWS3", "Writing to file");
File f = new File("/storage/sdcard0/resume-upload");
FileOutputStream fos;
try {
if (f.exists() == false)
f.createNewFile();
fos = new FileOutputStream(f);
arg0.serialize(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
I noticed that the onPersistableTransfer method is only called once, so I don't know how all the received bytes are serialized to the disk.
Any advices on how to get PersistableDownload to work? I'm using the SDK 2.1, with a real cell phone (Android 4.4.4) and Eclipse.
From the above code, I see that you are passing the partially downloaded image file to resume the download process.
if(file.exists()) {
try {
fis = new FileInputStream(file);
PersistableDownload persistableUpload = PersistableTransfer.deserializeFrom(fis);
Download meuDown = tx.resumeDownload(persistableUpload);
} catch (Exception e1) {
e1.printStackTrace();
}
}
Here file is referring to the partially downloaded image file. You will need to pass the file "/storage/sdcard0/resume-upload" to resume the upload.

Unable to download file created by my app on Google Drive, But can get the metadata of that file

I followed all the steps mentioned in google drive sdk. I created a sample application on my device(android, running jelly bean) and am able to upload a file on to drive. When trying to download the same file, I am able to get the meta data like fileID, fileTitle, fileDownloadURL etc but not able to download the content. I get 401 Unauthorized error.
My app AUTH SCOPE is AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/drive.file";
I am doing the following to get the OAUTH Token:
AccountManager am = AccountManager.get(this);
Bundle options = new Bundle();
am.getAuthToken(
mAccount,
AUTH_TOKEN_TYPE,
options,
this,
new OnTokenAcquired(),
new Handler(){
#Override
public void handleMessage(Message msg) {
invadiateToken();
super.handleMessage(msg);
}
});
Based on the token this is how I build the Drive object
Drive buildService(final String AuthToken) {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JsonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey(API_KEY);
driveRequest.setOauthToken(AuthToken);
}
});
return b.build();
}
I am able to upload the file using the following code:
private void uploadLocalFileToDrive(Drive service) throws IOException{
// File's metadata.
String mimeType = "text/plain";
File body = new File();
body.setTitle("myText.txt");
body.setDescription("sample app by varun");
body.setMimeType("text/plain");
// File's content.
java.io.File fileContent = new java.io.File(mInternalFilePath);
FileContent mediaContent = new FileContent(mimeType, fileContent);
service.files().insert(body, mediaContent).execute();
}
While trying to download the same file uploaded by this app, I get a 401 unauthorized error at this line HttpResponse resp = service.getRequestFactory().buildGetRequest(url).execute() from the following code snippet
private void downloadFileFromDrive(Drive service) throws IOException {
Files.List request;
request = service.files().list();
do {
FileList files = request.execute();
for(File file:files.getItems()){
String fieldId = file.getId();
String title = file.getTitle();
Log.e("MS", "MSV:: Title-->"+title+" FieldID-->"+fieldId+" DownloadURL-->"+file.getDownloadUrl());
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0 ) {
GenericUrl url = new GenericUrl(file.getDownloadUrl());
HttpResponse resp = service.getRequestFactory().buildGetRequest(url).execute();
InputStream isd = resp.getContent();
Log.e("MS", "MSV:: FileOutPutStream--->"+getFilesDir().getAbsolutePath()+"/downloaded.txt");
} else {
Log.e("MS", "MSV:: downloadURL for this file is null");
}
}
request.setPageToken(files.getNextPageToken());
} while (request.getPageToken()!=null && request.getPageToken().length()>0);
}
Can anyone help me out and let me know what I am doing wrong???
This is a known issue that will be resolved with the release of the Google Play Services APIs.
Since your application is authorized for the https://www.googleapis.com/auth/drive.file scope, and the download endpoint doesn't support the ?key= query parameter, there is no way for our server to know which project is issuing the request (to make sure the app has authorization to read this file's content).
In the meantime, the only workaround I can recommend is using the broad scope: https://www.googleapis.com/auth/drive. Please use only that while developing your application and waiting for the Google Play Services to be released.
To learn more about how you will be able to use the new authorization APIs in Android, you might be interested in those 2 Google I/O talks: Building Android Applications that Use Web APIs and
Writing Efficient Drive Apps for Android
I have answered this question, and all related Drive on Android questions, over here:
Android Open and Save files to/from Google Drive SDK
In that answer, I posted code for a method that I used to download files from Google Drive (if the following code by itself isn't clear, have a look at the complete answer that I linked to.)
private java.io.File downloadGFileToJFolder(Drive drive, String token, File gFile, java.io.File jFolder) throws IOException {
if (gFile.getDownloadUrl() != null && gFile.getDownloadUrl().length() > 0 ) {
if (jFolder == null) {
jFolder = Environment.getExternalStorageDirectory();
jFolder.mkdirs();
}
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(gFile.getDownloadUrl());
get.setHeader("Authorization", "Bearer " + token);
HttpResponse response = client.execute(get);
InputStream inputStream = response.getEntity().getContent();
jFolder.mkdirs();
java.io.File jFile = new java.io.File(jFolder.getAbsolutePath() + "/" + getGFileName(gFile)); // getGFileName() is my own method... it just grabs originalFilename if it exists or title if it doesn't.
FileOutputStream fileStream = new FileOutputStream(jFile);
byte buffer[] = new byte[1024];
int length;
while ((length=inputStream.read(buffer))>0) {
fileStream.write(buffer, 0, length);
}
fileStream.close();
inputStream.close();
return jFile;
} catch (IOException e) {
// Handle IOExceptions here...
return null;
}
} else {
// Handle the case where the file on Google Drive has no length here.
return null;
}
}
I don't think we need any Access Token to download a file. I had the same problem, and this worked:
private class DownloadFile extends AsyncTask<Void, Long, Boolean> {
private com.google.api.services.drive.model.File driveFile;
private java.io.File file;
public DownloadFile(File driveFile) {
this.driveFile = driveFile;
}
#Override
protected Boolean doInBackground(Void... params) {
if (driveFile.getDownloadUrl() != null
&& driveFile.getDownloadUrl().length() > 0) {
try {
HttpResponse resp = mDriveService
.getRequestFactory()
.buildGetRequest(
new GenericUrl(driveFile.getDownloadUrl()))
.execute();
OutputStream os = new FileOutputStream(file);
CopyStream(resp.getContent(), os);
os.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
} else {
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
//use the file
}
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}

Categories

Resources