From 244d747c29066e1caf9c99693e6ad356931b231d Mon Sep 17 00:00:00 2001 From: Ang Li Date: Tue, 12 Feb 2019 19:03:32 -0800 Subject: Add api to remove account. (#108) --- .../mobly/snippet/bundled/AccountSnippet.java | 42 +++++++++++++++++++--- 1 file changed, 38 insertions(+), 4 deletions(-) (limited to 'src/main/java/com') diff --git a/src/main/java/com/google/android/mobly/snippet/bundled/AccountSnippet.java b/src/main/java/com/google/android/mobly/snippet/bundled/AccountSnippet.java index c7f576b..aac543a 100644 --- a/src/main/java/com/google/android/mobly/snippet/bundled/AccountSnippet.java +++ b/src/main/java/com/google/android/mobly/snippet/bundled/AccountSnippet.java @@ -23,7 +23,9 @@ import android.accounts.AccountsException; import android.content.ContentResolver; import android.content.Context; import android.content.SyncAdapterType; +import android.os.Build; import android.os.Bundle; +import androidx.annotation.RequiresApi; import androidx.test.platform.app.InstrumentationRegistry; import com.google.android.mobly.snippet.Snippet; import com.google.android.mobly.snippet.rpc.Rpc; @@ -78,10 +80,6 @@ public class AccountSnippet implements Snippet { /** * Adds a Google account to the device. * - *

TODO(adorokhine): Support adding accounts of other types with an optional 'type' kwarg. - * - *

TODO(adorokhine): Allow users to choose whether to enable/disable sync with a kwarg. - * * @param username Username of the account to add (including @gmail.com). * @param password Password of the account to add. */ @@ -152,6 +150,42 @@ public class AccountSnippet implements Snippet { mSyncStatusObserverHandles.add(handle); } + /** + * Removes an account from the device. + * + *

The account has to be Google account. + * + * @param username the username of the account to remove. + * @throws AccountSnippetException if removing the account failed. + */ + @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1) + @Rpc(description = "Remove a Google account.") + public void removeAccount(String username) throws AccountSnippetException { + if (!mAccountManager.removeAccountExplicitly(getAccountByName(username))) { + throw new AccountSnippetException("Failed to remove account '" + username + "'."); + } + } + + /** + * Get an existing account by its username. + * + *

Google account only. + * + * @param username the username of the account to remove. + * @return tHe account with the username. + * @throws AccountSnippetException if no account has the given username. + */ + private Account getAccountByName(String username) throws AccountSnippetException { + Account[] accounts = mAccountManager.getAccountsByType(GOOGLE_ACCOUNT_TYPE); + for (Account account : accounts) { + if (account.name.equals(username)) { + return account; + } + } + throw new AccountSnippetException( + "Account '" + username + "' does not exist on the device."); + } + /** * Checks to see if the SyncAdapter is whitelisted. * -- cgit v1.2.3