How do I use google drive API for sending and receiving audio? [closed]

2

I wanted to know how I can send and receive audio files via Google drive. I've never used the Google Drive API, I'm starting now.

I researched some examples on the Internet, but I could not. Some examples searched and indicated:

link

link

link

link

I basically want to report a Google Drive account, send and receive recordings via the Google Drive. If anyone could help me, I would be very grateful. Every tip is valid:)

Embrace and thank you for your attention.

My progress:

Outbuildings: ManifestPermissions:ItreportedintheexampletoimportapermissioncalledUSE_CREDENTIALS,butitdidnotappeartome,soI'mwithonlythesetwoimported...

<uses-permissionandroid:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />

Code: The code is experiencing an error in the following methods: response.getEntity (), gFile.getDownloadURL (), get.setHeader (), getGFileName (gFile), client.execute (), am.getAuthToken (am.getAccounts ()) [0], ..., nul);

I've seen the getGFileName (gFile) tutorial tells me to do it, but I do not know if the others I have to do on the hand either, or suddenly I did it 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.
    }
}

If someone can help me, the whole tip is valid. Hugs!

    
asked by anonymous 19.01.2016 / 13:47

0 answers