Java tutorial
/** * Copyright 2013 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.mariovinay.android.spartandrive.authentication; import android.accounts.AccountManager; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.IntentSender.SendIntentException; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.drive.Drive; import com.google.android.gms.plus.Plus; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.drive.DriveScopes; import java.util.Arrays; import java.util.Stack; //import com.google.api.services.drive.DriveScopes; /** * An abstract activity that handles authorization and connection to the Drive * services. */ public abstract class BaseActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private static final String TAG = "BaseDriveActivity"; /** * DriveId of an existing folder to be used as a parent folder in * folder operations samples. */ public static final String EXISTING_FOLDER_ID = "0By8cXyjHLkEtSlZBTTZ0emlyeWs"; //0By8cXyjHLkEtQUF0ZzQ2LTdULWc//0By8cXyjHLkEteWVURFU5X1F2dkU /** * DriveId of an existing file to be used in file operation samples.. */ public static final String EXISTING_FILE_ID = "0By8cXyjHLkEtTFhzMXNiOUpsb2s"; /** * Extra for account name. */ protected static final String EXTRA_ACCOUNT_NAME = "account_name"; /** * Request code for auto Google Play Services error resolution. */ protected static final int REQUEST_CODE_RESOLUTION = 1; /** * Next available request code. */ protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2; /** * Google API client. */ private GoogleApiClient mGoogleApiClient; static final int REQUEST_ACCOUNT_PICKER = 1000; static final int REQUEST_AUTHORIZATION = 1001; static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002; //private TextView mOutputText; GoogleAccountCredential mCredential; private static final String PREF_ACCOUNT_NAME = "accountName"; private static final String[] SCOPES = { DriveScopes.DRIVE_FILE, DriveScopes.DRIVE, DriveScopes.DRIVE_APPDATA, DriveScopes.DRIVE_METADATA }; private static Stack folderStack = new Stack(); @Override protected void onCreate(Bundle b) { super.onCreate(b); // Initialize credentials and service object. SharedPreferences settings = getPreferences(Context.MODE_PRIVATE); mCredential = GoogleAccountCredential.usingOAuth2(getApplicationContext(), Arrays.asList(SCOPES)) .setBackOff(new ExponentialBackOff()) .setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null)); } /** * Called when activity gets visible. A connection to Drive services need to * be initiated as soon as the activity is visible. Registers * {@code ConnectionCallbacks} and {@code OnConnectionFailedListener} on the * activities itself. */ @Override protected void onResume() { super.onResume(); if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Drive.API).addScope(Drive.SCOPE_FILE) .addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample .addApi(Plus.API).addScope(Plus.SCOPE_PLUS_LOGIN).addScope(Plus.SCOPE_PLUS_PROFILE) .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build(); mGoogleApiClient.connect(); } //if(!mGoogleApiClient.isConnected()) //mGoogleApiClient.connect(); if (isGooglePlayServicesAvailable()) { refreshResults(); } else { System.out .println("Google Play Services required: " + "after installing, close and relaunch this app."); } } /** * Handles resolution callbacks. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) { mGoogleApiClient.connect(); } switch (requestCode) { case REQUEST_GOOGLE_PLAY_SERVICES: if (resultCode != RESULT_OK) { isGooglePlayServicesAvailable(); } break; case REQUEST_ACCOUNT_PICKER: if (resultCode == RESULT_OK && data != null && data.getExtras() != null) { String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); if (accountName != null) { mCredential.setSelectedAccountName(accountName); SharedPreferences settings = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString(PREF_ACCOUNT_NAME, accountName); editor.apply(); } } else if (resultCode == RESULT_CANCELED) { System.out.println("Account unspecified."); } break; case REQUEST_AUTHORIZATION: if (resultCode != RESULT_OK) { chooseAccount(); } break; } } /** * Called when activity gets invisible. Connection to Drive service needs to * be disconnected as soon as an activity is invisible. */ @Override protected void onPause() { if (mGoogleApiClient != null) { mGoogleApiClient.disconnect(); } super.onPause(); } /** * Called when {@code mGoogleApiClient} is connected. */ @Override public void onConnected(Bundle connectionHint) { Log.i(TAG, "GoogleApiClient connected"); } /** * Called when {@code mGoogleApiClient} is disconnected. */ @Override public void onConnectionSuspended(int cause) { Log.i(TAG, "GoogleApiClient connection suspended"); } /** * Called when {@code mGoogleApiClient} is trying to connect but failed. * Handle {@code result.getResolution()} if there is a resolution is * available. */ @Override public void onConnectionFailed(ConnectionResult result) { Log.i(TAG, "GoogleApiClient connection failed: " + result.toString()); if (!result.hasResolution()) { // show the localized error dialog. GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show(); return; } try { result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION); } catch (SendIntentException e) { Log.e(TAG, "Exception while starting resolution activity", e); } } /** * Shows a toast message. */ public void showMessage(String message) { Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } /** * Getter for the {@code GoogleApiClient}. */ public GoogleApiClient getGoogleApiClient() { return mGoogleApiClient; } public static Stack getFolderStack() { return folderStack; } /** * Attempt to get a set of data from the Drive API to display. If the * email address isn't known yet, then call chooseAccount() method so the * user can pick an account. */ private void refreshResults() { if (mCredential.getSelectedAccountName() == null) { chooseAccount(); } else { if (isDeviceOnline()) { //new MakeRequestTask(mCredential).execute(); } else { System.out.println("No network connection available."); } } } /** * Starts an activity in Google Play Services so the user can pick an * account. */ private void chooseAccount() { startActivityForResult(mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER); } /** * Checks whether the device currently has a network connection. * @return true if the device has a network connection, false otherwise. */ private boolean isDeviceOnline() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return (networkInfo != null && networkInfo.isConnected()); } /** * Check that Google Play services APK is installed and up to date. Will * launch an error dialog for the user to update Google Play Services if * possible. * @return true if Google Play Services is available and up to * date on this device; false otherwise. */ private boolean isGooglePlayServicesAvailable() { final int connectionStatusCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) { showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode); return false; } else if (connectionStatusCode != ConnectionResult.SUCCESS) { return false; } return true; } /** * Display an error dialog showing that Google Play Services is missing * or out of date. * @param connectionStatusCode code describing the presence (or lack of) * Google Play Services on this device. */ void showGooglePlayServicesAvailabilityErrorDialog(final int connectionStatusCode) { Dialog dialog = GooglePlayServicesUtil.getErrorDialog(connectionStatusCode, this, REQUEST_GOOGLE_PLAY_SERVICES); dialog.show(); } public GoogleAccountCredential getRESTCredential() { return mCredential; } }