2
I wanted to know how I can send and receive audio files via Google drive. I never used the Google Drive API, I’m starting now.
I did some research on the Internet, but I couldn’t do it. Some Researched and Indicated Examples:
https://github.com/googledrive/android-quickstart
https://stackoverflow.com/questions/13094781/google-drive-unresolved-imports
http://www.programcreek.com/java-api-examples/index.php?api=com.google.api.client.http.FileContent
Basically I want to inform a Google Drive account, send and receive recordings by there. In case anyone can help me would be very grateful. Every hint is valid :)
Hug and thanks for your attention.
My progress:
Dependencies: Permissions of the Manifesto: He reported in the example to import a permission called USE_CREDENTIALS, but it did not appear to me, so I am with only these two imported. . .
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
Code: The code is error in the following methods: Response.getEntity(), gFile.getDownloadURL(), get.setHeader(), getGFileName(gFile), client.execute(), am.getAuthToken(am.getAccounts()[0], ..., nul);
From what I saw, getGFileName(gFile) the tutorial tells me to do, but I don’t know if the others I have to do on hand too, or suddenly I imported or did something wrong..
Code Below
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.content.Intent;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveRequest;
import com.google.api.services.drive.DriveScopes;
import org.apache.commons.httpclient.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AccountManager am = AccountManager.get(this);
am.getAuthToken(am.getAccounts()), "oauth2:" + DriveScopes.DRIVE, new Bundle(), true, new OnTokenAcquired(), null);//esta linha mostra o trecho "am.getAccounts())" sublinhado em vermelho mas quando clico, não apresenta nenhum erro. .
}
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
boolean alreadyTriedAgain;
File outFile; //sera o arquivo de envio
@Override
public void run(final AccountManagerFuture<Bundle> result) {
try {
final String token = result.getResult().getString(AccountManager.KEY_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("Minha chave de Api");//chave da API. . .
driveRequest.setOauthToken(token);
}
});
final Drive drive = b.build();
final com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
body.setTitle("My Test File");
body.setDescription("A Test File");
body.setMimeType("text/plain");
// final FileContent mediaContent = new FileContent("text/plain", "Arqiovp de envio");
final FileContent mediaContent = new FileContent("image/png", outFile);//outfile é o arquivo de envio. . .
new Thread(new Runnable() {
public void run() {
try {
com.google.api.services.drive.model.File file = drive.files().insert(body, mediaContent).execute();
alreadyTriedAgain = false; // Global boolean to make sure you don't repeatedly try too many times when the server is down or your code is faulty... they'll block requests until the next day if you make 10 bad requests, I found.
} catch (IOException e) {
if (!alreadyTriedAgain) {
alreadyTriedAgain = true;
AccountManager am = AccountManager.get(this);
am.invalidateAuthToken(am.getAccounts()[0].type, null); // Requires the permissions MANAGE_ACCOUNTS & USE_CREDENTIALS in the Manifest
am.getAuthToken(am.getAccounts())[0], "oauth2:" + DriveScopes.DRIVE, new Bundle(), true, new OnTokenAcquired(), null); //esta linha mostra o trecho "am.getAccounts())" sublinhado em vermelho mas quando clico, não apresenta nenhum erro. .
} else {
// Give up. Crash or log an error or whatever you want.
}
}
}
}).start();
Intent launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 3025);
return; // Not sure why... I wrote it here for some reason. Might not actually be necessary.
}
} catch (OperationCanceledException e) {
// Handle it...
} catch (AuthenticatorException e) {
// Handle it...
} catch (IOException e) {
// Handle it...
}
}
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 ) { //apresenta erro no getDownloadUrl(), não aparece esta opção no autoComplete enquanto digito, acho que devera ser implementado a mão . . .
if (jFolder == null) {
jFolder = Environment.getExternalStorageDirectory();
jFolder.mkdirs();
}
try {
HttpClient client = new HttpClient();//era assim "HttpClient client = new DefaultHttpClient();" mas como estava apresentando erros, deixei como está agora. .
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;
}
}
}
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 {
org.apache.http.client.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;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 3025) {
switch (resultCode) {
case RESULT_OK:
AccountManager am = AccountManager.get(activity);
am.getAuthToken(am.getAccounts())[0], "oauth2:" + DriveScopes.DRIVE, new Bundle(), true, new OnTokenAcquired(), null);
break;
case RESULT_CANCELED:
// This probably means the user refused to log in. Explain to them why they need to log in.
break;
default:
// This isn't expected... maybe just log whatever code was returned.
break;
}
} else {
// Your application has other intents that it fires off besides the one for Drive's log in if it ever reaches this spot. Handle it here however you'd like.
}
}
In case someone can help me, the whole tip is valid. Hug!
Not from calls, but for example. Storing a recorded audio and sending to the drive (like when you send an audio message over watts).
– CristianCotrena
See this answer on Soen. It’s pretty detailed, gives you a "north".
– user28595
Thanks for the tip, I’ll take a look here, whether you get it or not, warning soon :)
– CristianCotrena
Very well explained, but I’m not able to get the sha1 of my app, I’m using Android Studio, in case you know how I can get this information please let me know.
– CristianCotrena
I was able to generate sha1 by Command Prompt according to these instructions.. https://www.youtube.com/watch?v=ELEsytc5LyU I’ll keep trying here. Hug!
– CristianCotrena
Hi guys, good, until then I managed to generate the SHA1. I imported all jar informed in the link. I also managed to register the app in Google Cloud Platform under "API >> Credentials Manager", with this I generated an API key to use in the java code of the app. However, after that, I could not follow for that example, I edited the content of the question showing my progress so far. The code still has some errors, I informed by comments the error lines. If someone can help me from this stage, all help is valid, I would be very grateful. Hug!
– CristianCotrena