Google Drive api integration does not work. How do I fix it?

0

I want to integrate the google drive api into my app. it runs but does not connect, as if it did not receive the information that was sent. How do I solve this? The code is the google itself that makes available only that seems to be outdated and I can not recognize where the error is in their code.

    
asked by anonymous 19.04.2016 / 00:07

1 answer

1

It's kind of complicated to point out what's wrong!

Yet without an example, or link!

I made a simple example of how to create a file:

I will not go into the merits of creating credentials .

If in doubt, follow the link .

When generating your credentials, a .json ( client_secret_xxxxxxxxxx.apps.googleusercontent.com.json ) file will be made available, this should be added to the app folder of your project!

This library only works with apk's signed, so when you enter SHA1 , it must be generated with your keyStore.jks .

In order for your debug apk to be signed, add the following code in your grid:

android {
    signingConfigs {
        debug {
            keyAlias ’seuAlias'
            keyPassword ’senhaAlias'
            storeFile file(‘Caminho/keyStore.jks')
            storePassword ’senhaKeyStore'
        }
    }
}

Let's create an abstract class that will have GoogleApiClient , responsible for connecting to the drive:

BaseActivity.java

import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveFolder;



public abstract class BaseActivity extends AppCompatActivity implements  GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{


    // Codigo de retorno
    public static final int RESOLVE_CONNECTION_REQUEST_CODE = 112;
    // conecta ao drive
    protected  GoogleApiClient mGoogleApiClient;


    @Override
    protected void onStart() {
        super.onStart();
        // Se estiver nulo, vamos configurar
        if(mGoogleApiClient == null){
            mGoogleApiClient = new GoogleApiClient.Builder(this).
                    addApi(Drive.API)
                    .addScope(Drive.SCOPE_FILE)
                    .addScope(Drive.SCOPE_APPFOLDER)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
        }
        if(!mGoogleApiClient.isConnected()){
            mGoogleApiClient.connect(); // conectando ....
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode){
            // Caso seja o código que enviamos e for OK, tentamos conectar novamente
            case RESOLVE_CONNECTION_REQUEST_CODE:
                if(resultCode == RESULT_OK){
                    mGoogleApiClient.connect();
                }
                break;
        }
    }

    @Override
    protected void onPause() {
        // desconectamos
        if(null != mGoogleApiClient){
            mGoogleApiClient.disconnect();
        }
        super.onPause();
    }

    /**
     * Será invocado quando se conectar
     */
    @Override
    public void onConnected(@Nullable Bundle bundle) {

    }

    /**
     * será invocado so suspender a conexão
     */
    @Override
    public void onConnectionSuspended(int i) {
    }

    /**
     * Tratamento de falha de conexão
     */

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        if(connectionResult.hasResolution()){
            try {
                connectionResult.startResolutionForResult(this, RESOLVE_CONNECTION_REQUEST_CODE);
            } catch (IntentSender.SendIntentException e) {
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }else{
            Toast.makeText(this, "onConnectionFailed", Toast.LENGTH_SHORT).show();
        }
    }


    protected void showMessage(final String message){
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}

MainActivity.java

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.MetadataChangeSet;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class MainActivity extends BaseActivity {

    /**
     * Callback de criação de um arquivo
     */
    private final ResultCallback<DriveApi.DriveContentsResult> createFileCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
        @Override
        public void onResult(@NonNull final DriveApi.DriveContentsResult result) {

            // se não teve sucesso, exibimos o erro e saímos...
            if(!result.getStatus().isSuccess()){
                showMessage("Não foi possível criar o arquivo...");
                return;
            }
            final DriveContents driveContents = result.getDriveContents();
            new Thread(){
                @Override
                public void run() {
                    final OutputStream outputStream = driveContents.getOutputStream();
                    final Writer writer = new OutputStreamWriter(outputStream);
                    try {
                        final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
                        writer.write("Arquivo criado através de app em "+dateFormat.format(Calendar.getInstance().getTimeInMillis()));
                        writer.close();
                    } catch (IOException e) {
                        showMessage(e.getMessage());
                    }

                    MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle("AppFileCreate").setMimeType("text/plain").setStarred(true).build();
                    Drive.DriveApi.getRootFolder(mGoogleApiClient).createFile(mGoogleApiClient, changeSet, driveContents).setResultCallback(fileCallback);
                }
            }.start();
        }
    };

    /*
    * Calback  de Resultado (invocado após a criação)
     */

    final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
            ResultCallback<DriveFolder.DriveFileResult>() {
                @Override
                public void onResult(DriveFolder.DriveFileResult result) {
                    if (!result.getStatus().isSuccess()) {
                        showMessage("Error while trying to create the file");
                        return;
                    }
                    showMessage("Created a file with content: " + result.getDriveFile().getDriveId());
                }
            };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Vamos criar um arquivo
                Drive.DriveApi.newDriveContents(mGoogleApiClient)
                        .setResultCallback(createFileCallback);
            }
        });

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        super.onConnected(bundle);

    }


}
    
19.04.2016 / 20:26