Api: Line 316, 335, 347
Warning: Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission
) or explicitly handle a potential SecurityException
@SuppressLint("MissingPermission")
public static Pair<String, String> getCredentials(Context context) {
String username = Preferences.getUsername(context);
if (TextUtils.isEmpty(username)) {
return null;
}
AccountManager accountManager = AccountManager.get(context);
Account[] accounts = accountManager.getAccountsByType(BuildConfig.APPLICATION_ID);
for (Account account : accounts) {
if (TextUtils.equals(username, account.name)) {
return Pair.create(username, accountManager.getPassword(account));
}
}
return null;
}
@SuppressLint("MissingPermission")
public static void showLogin(Context context, AlertDialogBuilder alertDialogBuilder) {
Account[] accounts = AccountManager.get(context).getAccountsByType(BuildConfig.APPLICATION_ID);
if (accounts.length == 0) { // no accounts, ask to login or re-login
context.startActivity(new Intent(context, LoginActivity.class));
} else if (!TextUtils.isEmpty(Preferences.getUsername(context))) { // stale account, ask to re-login
context.startActivity(new Intent(context, LoginActivity.class));
} else { // logged out, choose from existing accounts to log in
showAccountChooser(context, alertDialogBuilder, accounts);
}
}
@SuppressLint("MissingPermission")
static void registerAccountsUpdatedListener(final Context context) {
AccountManager.get(context).addOnAccountsUpdatedListener(accounts -> {
String username = Preferences.getUsername(context);
if (TextUtils.isEmpty(username)) {
return;
}
for (Account account : accounts) {
if (TextUtils.equals(account.name, username)) {
return;
}
}
Preferences.setUsername(context, null);
}, null, true);
}