2

I want to save user's data in the background but I don't understand how to connect to the Drive API without user interaction.

From my understanding after the first connect

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstance);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Drive.API)
            .addScope(Drive.SCOPE_FILE)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}

I'd like to obtain a refresh token which I will use later on to get an access token which I'll use to connect to the API and save user's data. It doesn't look feasible with Drive API for Android

Also I'll appreciate if somebody points me towards how do it it the right way!

Dmitry
  • 1,484
  • 2
  • 15
  • 23

1 Answers1

1

To implement saving file to Drive from background service, you need to start an activity where you will be handling the activity result of the permission activity.

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
  if (resultCode == Activity.RESULT_OK) {
    // permission is given
    finish();
  } else {
    or show error
  }
}

To obtain a refresh token to allow long-term access, your app requests authorization to access resources which are identified by scopes. You need to add prompt=consent parameter to the authentication request. When prompt=consent is included, the consent screen is displayed every time the you logs into your app. The refresh token is only returned the first time on granting the application permission.

Based from this thread:

The refresh_token is only provided on the first authorization from the user. Subsequent authorizations, such as the kind you make while testing an OAuth2 integration, will not return the refresh_token again.

Then to generate access token using refresh token, you can refer to this question.

Community
  • 1
  • 1
abielita
  • 13,147
  • 2
  • 17
  • 59
  • Could you provide a code example with request for authorization for Google Drive? – Dmitry Feb 17 '16 at 05:25
  • You need to use the [OAuth 2.0 protocol](https://developers.google.com/identity/protocols/OAuth2) for authenticating a Google account and authorizing access to user data. Here is the [documentation](https://developers.google.com/drive/v2/web/about-auth) and [example](https://developers.google.com/drive/v2/web/auth/web-server#exchange_the_authorization_code_for_an_access_token). – abielita Feb 17 '16 at 05:36