com.google.android.gms.auth.api.signin.GoogleSignInClient Java Examples

The following examples show how to use com.google.android.gms.auth.api.signin.GoogleSignInClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BaseDemoActivity.java    From android-samples with Apache License 2.0 8 votes vote down vote up
/**
 * Starts the sign-in process and initializes the Drive client.
 */
protected void signIn() {
    Set<Scope> requiredScopes = new HashSet<>(2);
    requiredScopes.add(Drive.SCOPE_FILE);
    requiredScopes.add(Drive.SCOPE_APPFOLDER);
    GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
    if (signInAccount != null && signInAccount.getGrantedScopes().containsAll(requiredScopes)) {
        initializeDriveClient(signInAccount);
    } else {
        GoogleSignInOptions signInOptions =
                new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                  .requestScopes(Drive.SCOPE_FILE)
                  .requestScopes(Drive.SCOPE_APPFOLDER)
                  .build();
        GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
        startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
    }
}
 
Example #2
Source File: AuthUtil.java    From SEAL-Demo with MIT License 6 votes vote down vote up
/**
 * Allows to logout from Google account
 *
 * @param context the activity context
 */
private static void logoutGoogleProvider(final Context context) {
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(context.getString(R.string.googleClientId))
            .requestProfile()
            .build();
    // Build a GoogleSignInClient with the options specified by gso.
    GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(context, gso);
    // Check for existing Google Sign In account, if the user is already signed in
    // the GoogleSignInAccount will be non-null.
    GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(context);
    if (account != null) {
        mGoogleSignInClient.signOut()
                .addOnCompleteListener(((Activity) context), new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        ApplicationState.setIsKeysCreated(false);
                        // delete all user info
                        deleteUserTokenAndInfo(context);
                        // load sign in
                        Intent myIntent = new Intent(context, SignInActivity.class);
                        ((Activity) context).startActivityForResult(myIntent, SIGN_IN_ACTIVITY_REQUEST_CODE);
                    }
                });
    }
}
 
Example #3
Source File: PlayGamesPlugin.java    From play_games with MIT License 6 votes vote down vote up
private void signOut() {
    GoogleSignInOptions.Builder builder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
    GoogleSignInOptions opts = builder.build();
    GoogleSignInClient signInClient = GoogleSignIn.getClient(registrar.activity(), opts);
    signInClient.signOut().addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            currentAccount = null;
            Map<String, Object> successMap = new HashMap<>();
            successMap.put("type", "SUCCESS");
            result(successMap);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            error("ERROR_SIGN_OUT", e);
            Log.i(TAG, "Failed to signout", e);
        }
    });

}
 
Example #4
Source File: LoadingActivity.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
private void signInSilently() {
    GoogleSignInOptions signInOptions = GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN;
    GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
    if (GoogleSignIn.hasPermissions(account, signInOptions.getScopeArray())) {
        googleSignedIn(account);
    } else {
        GoogleSignInClient signInClient = GoogleSignIn.getClient(this, signInOptions);
        signInClient.silentSignIn().addOnCompleteListener(this, task -> {
            if (task.isSuccessful()) {
                googleSignedIn(task.getResult());
            } else {
                if (Prefs.getBoolean(PK.SHOULD_PROMPT_GOOGLE_PLAY, true)) {
                    Intent intent = signInClient.getSignInIntent();
                    startActivityForResult(intent, GOOGLE_SIGN_IN_CODE);
                }
            }
        });
    }
}
 
Example #5
Source File: GoogleAuth.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Promise<Void> signOut() {
    return FuturePromise.when(new Consumer<FuturePromise<Void>>() {
        @Override
        public void accept(final FuturePromise<Void> voidFuturePromise) {
            GoogleSignInClient client = GoogleSignIn.getClient((AndroidApplication) Gdx.app, GoogleSignInOptionsFactory.factory());
            client.signOut().addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        voidFuturePromise.doComplete(null);
                    } else {
                        voidFuturePromise.doFail(task.getException());
                    }
                }
            });
        }
    });
}
 
Example #6
Source File: GoogleAuth.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Promise<Void> revokeAccess() {
    return FuturePromise.when(new Consumer<FuturePromise<Void>>() {
        @Override
        public void accept(final FuturePromise<Void> voidFuturePromise) {
            GoogleSignInClient client = GoogleSignIn.getClient((AndroidApplication) Gdx.app, GoogleSignInOptionsFactory.factory());
            client.revokeAccess().addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        voidFuturePromise.doComplete(null);
                    } else {
                        voidFuturePromise.doFail(task.getException());
                    }
                }
            });
        }
    });
}
 
Example #7
Source File: GoogleAuthTest.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@Override
public void setup() throws Exception {
    super.setup();
    PowerMockito.mockStatic(GoogleSignInOptions.class);
    PowerMockito.mockStatic(GoogleSignInClient.class);
    PowerMockito.mockStatic(StringResource.class);
    PowerMockito.mockStatic(GoogleSignIn.class);
    googleSignInClient = Mockito.mock(GoogleSignInClient.class);
    Mockito.when(GoogleSignIn.getClient(Mockito.any(Context.class), Mockito.any(GoogleSignInOptions.class))).thenReturn(googleSignInClient);
    Mockito.when(GoogleSignIn.getClient(Mockito.any(Activity.class), Mockito.any(GoogleSignInOptions.class))).thenReturn(googleSignInClient);
    Mockito.when(StringResource.getStringResourceByName(Mockito.anyString())).thenReturn("test");
}
 
Example #8
Source File: BaseDemoActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the sign-in process and initializes the Drive client.
 */
private void signIn() {
    GoogleSignInOptions signInOptions =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestScopes(Drive.SCOPE_FILE)
                    .requestScopes(Drive.SCOPE_APPFOLDER)
                    .build();
    GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
    startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
 
Example #9
Source File: MainActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Starts a sign-in activity using {@link #REQUEST_CODE_SIGN_IN}.
 */
private void requestSignIn() {
    Log.d(TAG, "Requesting sign-in");

    GoogleSignInOptions signInOptions =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail()
                    .requestScopes(new Scope(DriveScopes.DRIVE_FILE))
                    .build();
    GoogleSignInClient client = GoogleSignIn.getClient(this, signInOptions);

    // The result of the sign-in Intent is handled in onActivityResult.
    startActivityForResult(client.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
 
Example #10
Source File: MainActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/** Build a Google SignIn client. */
private GoogleSignInClient buildGoogleSignInClient() {
  GoogleSignInOptions signInOptions =
      new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
          .requestScopes(Drive.SCOPE_FILE)
          .build();
  return GoogleSignIn.getClient(this, signInOptions);
}
 
Example #11
Source File: MainActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the sign in process to get the current user and authorize access to Drive.
 */
private void signIn() {
    GoogleSignInOptions signInOptions =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestScopes(Drive.SCOPE_FILE)
                    .build();
    GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
    startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
 
Example #12
Source File: MainActivity.java    From drive-android-quickstart with Apache License 2.0 5 votes vote down vote up
/** Build a Google SignIn client. */
private GoogleSignInClient buildGoogleSignInClient() {
  GoogleSignInOptions signInOptions =
      new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
          .requestScopes(Drive.SCOPE_FILE)
          .build();
  return GoogleSignIn.getClient(this, signInOptions);
}
 
Example #13
Source File: PlayGames.java    From remixed-dungeon with GNU General Public License v3.0 5 votes vote down vote up
public void disconnect() {
	Preferences.INSTANCE.put(Preferences.KEY_USE_PLAY_GAMES, false);

	GoogleSignInClient signInClient = GoogleSignIn.getClient(Game.instance(),
			GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
	signInClient.signOut().addOnCompleteListener(Game.instance().serviceExecutor,
			task -> {
				signedInAccount = null;
				// at this point, the user is signed out.
			});
}
 
Example #14
Source File: RemoteBackup.java    From Database-Backup-Restore with Apache License 2.0 5 votes vote down vote up
private GoogleSignInClient buildGoogleSignInClient() {
    GoogleSignInOptions signInOptions =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestScopes(Drive.SCOPE_FILE)
                    .build();
    return GoogleSignIn.getClient(activity, signInOptions);
}
 
Example #15
Source File: BaseMainDbActivity.java    From dbsync with Apache License 2.0 5 votes vote down vote up
/**
 * Build a Google SignIn client.
 */
private GoogleSignInClient buildGoogleSignInClient() {
    GoogleSignInOptions signInOptions =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestScopes(new Scope(DriveScopes.DRIVE))
                    .requestScopes(new Scope(DriveScopes.DRIVE_FILE))
                    .requestScopes(new Scope(DriveScopes.DRIVE_METADATA))
                    .requestScopes(new Scope(DriveScopes.DRIVE_READONLY))
                    .requestScopes(new Scope(DriveScopes.DRIVE_METADATA_READONLY))
                    .requestScopes(new Scope(DriveScopes.DRIVE_PHOTOS_READONLY))
                    .requestEmail()
                    .build();
    return GoogleSignIn.getClient(this, signInOptions);
}
 
Example #16
Source File: SignInController.java    From PGSGP with MIT License 5 votes vote down vote up
public void signIn(final GoogleSignInClient googleSignInClient) {
    Pair<Boolean, String> connection = connectionController.isConnected();
    if (connection.first) {
        godotCallbacksUtils.invokeGodotCallback(GodotCallbacksUtils.SIGNIN_SUCCESSFUL, new Object[]{connection.second});
        enablePopUps();
    } else {
        googleSignInClient
                .silentSignIn()
                .addOnCompleteListener(activity, new OnCompleteListener<GoogleSignInAccount>() {
                    @Override
                    public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
                        if (task.isSuccessful()) {
                            GoogleSignInAccount googleSignInAccount = task.getResult();
                            String accId = "";
	            if (googleSignInAccount != null && googleSignInAccount.getId() != null) {
	            	accId = googleSignInAccount.getId();
	            }

                            godotCallbacksUtils.invokeGodotCallback(GodotCallbacksUtils.SIGNIN_SUCCESSFUL, new Object[]{accId});
                            enablePopUps();
                        } else {
                            Intent intent = googleSignInClient.getSignInIntent();
                            activity.startActivityForResult(intent, RC_SIGN_IN);
                        }
                    }
                });
    }
}
 
Example #17
Source File: AndroidGoogleAccount.java    From QtAndroidTools with MIT License 5 votes vote down vote up
private GoogleSignInClient getSignInClient(String ScopeName)
{
    GoogleSignInOptions.Builder SignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN);
    if(ScopeName.isEmpty() == false) SignInOptions.requestScopes(new Scope(ScopeName));
    SignInOptions.requestEmail();

    return GoogleSignIn.getClient(mActivityInstance, SignInOptions.build());
}
 
Example #18
Source File: PlayGamesPlugin.java    From play_games with MIT License 5 votes vote down vote up
private void silentSignIn(final GoogleSignInClient signInClient) {
    signInClient.silentSignIn().addOnSuccessListener(new OnSuccessListener<GoogleSignInAccount>() {
        @Override
        public void onSuccess(GoogleSignInAccount googleSignInAccount) {
            handleSuccess(googleSignInAccount);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.i(TAG, "Failed to silent signin, trying explicit signin", e);
            explicitSignIn(signInClient);
        }
    });
}
 
Example #19
Source File: PlayGamesPlugin.java    From play_games with MIT License 5 votes vote down vote up
private void signIn(boolean requestEmail, boolean scopeSnapshot) {
    GoogleSignInOptions.Builder builder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
    if (requestEmail) {
        builder.requestEmail();
    }
    if (scopeSnapshot) {
        builder.requestScopes(Drive.SCOPE_APPFOLDER);
    }
    GoogleSignInOptions opts = builder.build();
    GoogleSignInClient signInClient = GoogleSignIn.getClient(registrar.activity(), opts);
    silentSignIn(signInClient);
}
 
Example #20
Source File: SignInController.java    From PGSGP with MIT License 5 votes vote down vote up
public void signOut(GoogleSignInClient googleSignInClient) {
    googleSignInClient.signOut().addOnCompleteListener(activity, new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                godotCallbacksUtils.invokeGodotCallback(GodotCallbacksUtils.SIGN_OUT_SUCCESS, new Object[]{});
            } else {
                godotCallbacksUtils.invokeGodotCallback(GodotCallbacksUtils.SIGN_OUT_FAILED, new Object[]{});
            }
        }
    });
}
 
Example #21
Source File: RemoteBackup.java    From Database-Backup-Restore with Apache License 2.0 4 votes vote down vote up
private void signIn() {
    Log.i(TAG, "Start sign in");
    GoogleSignInClient GoogleSignInClient = buildGoogleSignInClient();
    activity.startActivityForResult(GoogleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
 
Example #22
Source File: PlayGamesPlugin.java    From play_games with MIT License 4 votes vote down vote up
private void explicitSignIn(GoogleSignInClient signInClient) {
    Intent intent = signInClient.getSignInIntent();
    registrar.activity().startActivityForResult(intent, RC_SIGN_IN);
}
 
Example #23
Source File: MainActivity.java    From android-samples with Apache License 2.0 4 votes vote down vote up
/** Start sign in activity. */
private void signIn() {
  Log.i(TAG, "Start sign in");
  GoogleSignInClient GoogleSignInClient = buildGoogleSignInClient();
  startActivityForResult(GoogleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
 
Example #24
Source File: AuthenticationManager.java    From ground-android with Apache License 2.0 4 votes vote down vote up
@NonNull
private GoogleSignInClient getGoogleSignInClient(Activity activity) {
  // TODO: Use app context instead of activity?
  return GoogleSignIn.getClient(activity, googleSignInOptions);
}
 
Example #25
Source File: ConflictResolver.java    From android-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Initiate the resolution process by connecting the GoogleApiClient.
 */
void resolve() {
    // [START drive_android_resolve_conflict]
    // A new DriveResourceClient should be created to handle each new CompletionEvent since each
    // event is tied to a specific user account. Any DriveFile action taken must be done using
    // the correct account.
    GoogleSignInOptions.Builder signInOptionsBuilder =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestScopes(Drive.SCOPE_FILE)
                    .requestScopes(Drive.SCOPE_APPFOLDER);
    if (mConflictedCompletionEvent.getAccountName() != null) {
        signInOptionsBuilder.setAccountName(mConflictedCompletionEvent.getAccountName());
    }
    GoogleSignInClient signInClient =
            GoogleSignIn.getClient(mContext, signInOptionsBuilder.build());
    signInClient.silentSignIn()
            .continueWith(mExecutorService,
                    (Continuation<GoogleSignInAccount, Void>) signInTask -> {
                        mDriveResourceClient = Drive.getDriveResourceClient(
                                mContext, signInTask.getResult());
                        mBaseContent = ConflictUtil.getStringFromInputStream(
                                mConflictedCompletionEvent.getBaseContentsInputStream());
                        mModifiedContent = ConflictUtil.getStringFromInputStream(
                                mConflictedCompletionEvent
                                        .getModifiedContentsInputStream());
                        return null;
                    })
            .continueWithTask(mExecutorService,
                    task -> {
                        DriveId driveId = mConflictedCompletionEvent.getDriveId();
                        return mDriveResourceClient.openFile(
                                driveId.asDriveFile(), DriveFile.MODE_READ_ONLY);
                    })
            .continueWithTask(mExecutorService,
                    task -> {
                        mDriveContents = task.getResult();
                        InputStream serverInputStream = task.getResult().getInputStream();
                        mServerContent =
                                ConflictUtil.getStringFromInputStream(serverInputStream);
                        return mDriveResourceClient.reopenContentsForWrite(mDriveContents);
                    })
            .continueWithTask(mExecutorService,
                    task -> {
                        DriveContents contentsForWrite = task.getResult();
                        mResolvedContent = ConflictUtil.resolveConflict(
                                mBaseContent, mServerContent, mModifiedContent);

                        OutputStream outputStream = contentsForWrite.getOutputStream();
                        try (Writer writer = new OutputStreamWriter(outputStream)) {
                            writer.write(mResolvedContent);
                        }

                        // It is not likely that resolving a conflict will result in another
                        // conflict, but it can happen if the file changed again while this
                        // conflict was resolved. Since we already implemented conflict
                        // resolution and we never want to miss user data, we commit here
                        // with execution options in conflict-aware mode (otherwise we would
                        // overwrite server content).
                        ExecutionOptions executionOptions =
                                new ExecutionOptions.Builder()
                                        .setNotifyOnCompletion(true)
                                        .setConflictStrategy(
                                                ExecutionOptions
                                                        .CONFLICT_STRATEGY_KEEP_REMOTE)
                                        .build();

                        // Commit resolved contents.
                        MetadataChangeSet modifiedMetadataChangeSet =
                                mConflictedCompletionEvent.getModifiedMetadataChangeSet();
                        return mDriveResourceClient.commitContents(contentsForWrite,
                                modifiedMetadataChangeSet, executionOptions);
            })
            .addOnSuccessListener(aVoid -> {
                mConflictedCompletionEvent.dismiss();
                Log.d(TAG, "resolved list");
                sendResult(mModifiedContent);
            })
            .addOnFailureListener(e -> {
                // The contents cannot be reopened at this point, probably due to
                // connectivity, so by snoozing the event we will get it again later.
                Log.d(TAG, "Unable to write resolved content, snoozing completion event.",
                        e);
                mConflictedCompletionEvent.snooze();
                if (mDriveContents != null) {
                    mDriveResourceClient.discardContents(mDriveContents);
                }
            });
    // [END drive_android_resolve_conflict]
}