Search code examples
javaandroidgoogle-drive-apigoogle-drive-android-api

Connecting and Authorizing with the Google APIs Java Client


I get confused with the guild Connecting and Authorizing with the Google APIs Java Client

I have written the following code and get the service instance

GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
credential.setSelectedAccountName(accountName);
Drive service = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();

I don't know what the next step is.

It seem to me that the Drive class in this code is different class from Drive in Google API for Android

Then should I follow the Drive REST API or Drive API for Android.


Solution

  • These are 2 different APIs, and it is not recommended to mix them together. The REST Api (v2 and v3) use

    com.google.api.services.drive.Drive mGOOSvc =
      new Drive.Builder(
        AndroidHttp.newCompatibleTransport(),
        new GsonFactory(),
        GoogleAccountCredential.usingOAuth2(Context, Collections.singletonList(DriveScopes.DRIVE_FILE))
       ....
      )
    .build();
    

    to access GooDrive services, i.e. you call the methods like:

    mGOOSvc.files().get()...
    mGOOSvc.files().list()....
    mGOOSvc.files().insert()...
    mGOOSvc.files().patch()...
    mGOOSvc.files().update()...
    mGOOSvc.getRequestFactory().buildGetRequest()...
    

    using this service that you instantiated.

    On the other hand, GDAA uses a different construct:

    com.google.android.gms.common.api.GoogleApiClient mGAC 
      = new GoogleApiClient.Builder(Context)
      .addApi(Drive.API)
      .addScope(Drive.SCOPE_FILE)
      .addScope(Drive.SCOPE_APPFOLDER)
      .addConnectionCallbacks( new GoogleApiClient.ConnectionCallbacks() {...})
      .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {...})
      ....
      .build();
    

    to create GoogleApiClient mGAC used to access GDAA like so:

    mGAC.connect() / disconnect()
    Drive.DriveApi.getRootFolder(mGAC)...
    Drive.DriveApi.getAppFolder(mGAC)...
    Drive.DriveApi.getFolder(mGAC, ...)...
    Drive.DriveApi.query(mGAC, ...)...
    DriveFolder.createFile(mGAC, ..., ...)
    ...
    

    As I mentioned above, DO NOT MIX the two APIs unless you know what the implications are (GDAA is a local service - see Drive Local Context in Lifecycle of a Drive file here, the REST Api talks directly to the network).

    There are 2 examples of these two APIs available on GitHub, solving the same problem (building and reading a directory tree) here (REST) and here (GDAA). The MainActivity of these two is pretty much the same, and it calls methods of wrapper classes REST or GDAA respectively.

    Good Luck