Google drive api integration doesn’t work. how do I fix it?

Asked

Viewed 596 times

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 fix this? The code is the google itself that makes available only it seems to be outdated and I can not recognize where is the error in their code.

  • Did you sign your apk? Could you show how you do the connection? Put the . json file generated by the console?

1 answer

1

It’s a little 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 won’t get into the merit of creating the credentials.

If in doubt, follow the link.

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

This library only works with signed apk’s, so when you inform the SHA1, this must be generated with your Keystore.jks.

For your debug apk to be signed, add the following code into 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 the GoogleApiClient, responsible for connecting to the drive:

Basectivity.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);

    }


}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.