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

The following examples show how to use android.accounts.AccountManager#getAccountsByType() . 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: AuthHelper.java    From android-atleap with Apache License 2.0 6 votes vote down vote up
/**
 * Check if the specified account exist
 * @param context context
 * @param account account to check
 * @return <code>true</code> if account exist
 */
public static boolean isAccountExist(Context context, Account account) {
    if (account == null)
        return false;
    final AccountManager accountManager = AccountManager.get(context);
    Account[] accounts = accountManager.getAccountsByType(account.type);
    if (accounts == null || accounts.length == 0) {
        return false;
    } else {
        for (Account a : accounts) {
            if (a.equals(account))
                return true;
        }
        return false;
    }
}
 
Example 2
Source File: ContactListFragment.java    From haxsync with GNU General Public License v2.0 6 votes vote down vote up
private void showSyncIndicator(){
	AccountManager am = AccountManager.get(getActivity());
	Account account = am.getAccountsByType(getActivity().getString(R.string.ACCOUNT_TYPE))[0];
	final boolean isSyncing = (ContentResolver.isSyncActive(account, "com.android.contacts") || ContentResolver.isSyncPending(account, "com.android.contacts"));
	getActivity().runOnUiThread(new Runnable() {
		@Override
		public void run() {
			if (isSyncing) {
				if (((LinearLayout) getView()).getChildCount() == 1)
				((LinearLayout) getView()).addView(LayoutInflater.from(getActivity()).inflate(R.layout.contact_loading_indicator, null), 0);
			} else{
				if (((LinearLayout) getView()).getChildCount() > 1)
					((LinearLayout) getView()).removeViewAt(0);
			}
		}
	});
}
 
Example 3
Source File: AppUtils.java    From android with Apache License 2.0 6 votes vote down vote up
static List<String> getEmailAddresses(Context context, int limit) {
    ArrayList<String> emails = new ArrayList<String>();
    AccountManager am = AccountManager.get(context);
    if (am == null) {
        return emails;
    }
    Account[] accounts = am.getAccountsByType("com.google");
    if (accounts == null || accounts.length == 0) {
        return emails;
    }
    for (Account a : accounts) {
        if (a.name == null || a.name.length() == 0) {
            continue;
        }
        emails.add(a.name.trim().toLowerCase());
    }
    while (emails.size() > limit) {
        emails.remove(emails.size() - 1);
    }
    return emails;
}
 
Example 4
Source File: UserInfo.java    From echo with GNU General Public License v3.0 6 votes vote down vote up
public static String getUserID(Context c) {
    final TelephonyManager tMgr = (TelephonyManager)c.getSystemService(Context.TELEPHONY_SERVICE);
    String id = tMgr.getDeviceId();
    if(id != null) {
        return "device-id:" + id;
    }

    AccountManager accountManager = AccountManager.get(c);
    Account[] accounts = accountManager.getAccountsByType("com.google");
    for (Account a: accounts) {
        if (a.name.contains("@gmail.com")) {
            return "email:" + a.name;
        }
    }

    return "android-id:" + Settings.Secure.getString(c.getContentResolver(), Settings.Secure.ANDROID_ID);
}
 
Example 5
Source File: MainActivity.java    From kolabnotes-android with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void onStatusChanged(int which) {
    AccountManager accountManager = AccountManager.get(this);
    Account[] accounts = accountManager.getAccountsByType(AuthenticatorActivity.ARG_ACCOUNT_TYPE);

    if (accounts.length <= 0) {
        return;
    }

    Account selectedAccount = null;

    ActiveAccount activeAccount = activeAccountRepository.getActiveAccount();

    for (Account acc : accounts) {
        String email = mAccountManager.getUserData(acc, AuthenticatorActivity.KEY_EMAIL);
        String folder = mAccountManager.getUserData(acc, AuthenticatorActivity.KEY_ROOT_FOLDER);
        if (activeAccount.getAccount().equalsIgnoreCase(email) && activeAccount.getRootFolder().equalsIgnoreCase(folder)) {
            selectedAccount = acc;
            break;
        }
    }

    overviewFragment.refreshFinished(selectedAccount);
}
 
Example 6
Source File: Util.java    From android-ponewheel with MIT License 6 votes vote down vote up
public static String getUsername(Context c) {
    AccountManager manager = AccountManager.get(c);
    Account[] accounts = manager.getAccountsByType("com.google");
    List<String> possibleEmails = new LinkedList<String>();

    for (Account account : accounts) {
        // TODO: Check possibleEmail against an email regex or treat
        // account.name as an email address only for certain account.type values.
        possibleEmails.add(account.name);
    }

    if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
        String email = possibleEmails.get(0);
        String[] parts = email.split("@");

        if (parts.length > 1)
            return parts[0];
    }
    return null;
}
 
Example 7
Source File: AppAccountAuthenticator.java    From account-authenticator with Apache License 2.0 5 votes vote down vote up
private boolean isAccountAvailable(Account account, AccountManager accountManager) {
    Account[] availableAccounts = accountManager.getAccountsByType(account.type);
    for (Account availableAccount : availableAccounts) {
        if (account.name.equals(availableAccount.name) && account.type.equals(availableAccount.type)) {
            return true;
        }
    }
    return false;
}
 
Example 8
Source File: SyncAdapter.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressLint("MissingPermission")
public static void setSyncPeriod(
        IGISApplication application,
        Bundle extras,
        long pollFrequency)
{
    Context context = ((Context) application).getApplicationContext();
    final AccountManager accountManager = AccountManager.get(context);
    Log.d(TAG, "SyncAdapter: AccountManager.get(" + context + ")");

    for (Account account : accountManager.getAccountsByType(application.getAccountsType())) {
        ContentResolver.addPeriodicSync(account, application.getAuthority(), extras, pollFrequency);
    }
}
 
Example 9
Source File: AuthenticationUtil.java    From palmsuda with Apache License 2.0 5 votes vote down vote up
public synchronized static void updateAccountParameter(Context context,
		String key, String value) {
	AccountManager mAccountManager = AccountManager.get(context);
	Account[] mAccounts = mAccountManager
			.getAccountsByType(Constants.ACCOUNT_TYPE);

	mAccountManager.setUserData(mAccounts[0], key, value);
}
 
Example 10
Source File: PreferencesActivity.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
private Account getSelectedAccount() {
    String accountName = MyPreferences.getGoogleDriveAccount(this);
    if (accountName != null) {
        AccountManager accountManager = AccountManager.get(this);
        Account[] accounts = accountManager.getAccountsByType("com.google");
        for (Account account : accounts) {
            if (accountName.equals(account.name)) {
                return account;
            }
        }
    }
    return null;
}
 
Example 11
Source File: PeopleServiceImpl.java    From android_packages_apps_GmsCore with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("MissingPermission")
@Override
public void loadOwners(final IPeopleCallbacks callbacks, boolean var2, boolean var3, final String accountName, String var5, int sortOrder) {
    Log.d(TAG, "loadOwners: " + var2 + ", " + var3 + ", " + accountName + ", " + var5 + ", " + sortOrder);
    if (context.checkCallingPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
        PackageUtils.assertExtendedAccess(context);
    }
    AccountManager accountManager = AccountManager.get(context);
    Bundle accountMetadata = new Bundle();
    String accountType = AuthConstants.DEFAULT_ACCOUNT_TYPE;
    for (Account account : accountManager.getAccountsByType(accountType)) {
        if (accountName == null || account.name.equals(accountName)) {
            accountMetadata.putParcelable(account.name, new AccountMetadata());
        }
    }
    Bundle extras = new Bundle();
    extras.putBundle("account_metadata", accountMetadata);
    try {
        DatabaseHelper databaseHelper = new DatabaseHelper(context);
        DataHolder dataHolder = new DataHolder(databaseHelper.getOwners(), 0, extras);
        Log.d(TAG, "loadOwners[result]: " + dataHolder);
        callbacks.onDataHolder(0, extras, dataHolder);
        databaseHelper.close();
    } catch (Exception e) {
        Log.w(TAG, e);
    }
}
 
Example 12
Source File: User.java    From narrate-android with Apache License 2.0 5 votes vote down vote up
public static Account getAccount() {
    AccountManager accountManager = AccountManager.get(GlobalApplication.getAppContext());
    Account[] accs = accountManager.getAccountsByType(ACCOUNT_TYPE);
    if ( accs != null && accs.length > 0 )
        return accs[0];
    else {
        // recreate the user account if it is null
        Account acc = new Account(Settings.getEmail(), ACCOUNT_TYPE);
        accountManager.addAccountExplicitly(acc, null, null);
        return acc;
    }
}
 
Example 13
Source File: MainMenu.java    From Coloring-book with Apache License 2.0 4 votes vote down vote up
private boolean deviceHasGoogleAccount() {
    AccountManager accMan = AccountManager.get(this);
    Account[] accArray = accMan.getAccountsByType("com.google");
    return accArray.length >= 1 ? true : false;
}
 
Example 14
Source File: AuthenticationUtil.java    From palmsuda with Apache License 2.0 4 votes vote down vote up
public static PalmAccount getAccountData(Context context) {
	AccountManager mAccountManager = AccountManager.get(context);

	Account[] mAccounts = mAccountManager
			.getAccountsByType(Constants.ACCOUNT_TYPE);
	if (mAccounts.length > 0) {
		PalmAccount cityAccount = new PalmAccount();
		cityAccount.setAccountName(mAccountManager.getUserData(
				mAccounts[0], Params.PARAMS_LOGIN_ID));
		cityAccount.setPassword(mAccountManager.getUserData(mAccounts[0],
				Params.PARAMS_LOGIN_PW));

		cityAccount.setBirthDate(mAccountManager.getUserData(mAccounts[0],
				Params.PARAMS_USER_BIRTHDAY));
		cityAccount.setCityName(mAccountManager.getUserData(mAccounts[0],
				Params.PARAMS_USER_CITY));
		cityAccount.setEmail(mAccountManager.getUserData(mAccounts[0],
				Params.PARAMS_USER_EMAIL));
		cityAccount.setNickname(mAccountManager.getUserData(mAccounts[0],
				Params.PARAMS_USER_NICK_NAME));
		cityAccount.setMkeywords(mAccountManager.getUserData(mAccounts[0],
				Params.PARAMS_USER_DESC));
		cityAccount.setImsi(mAccountManager.getUserData(mAccounts[0],
				Params.PARAMS_LOGIN_IMSI));
		cityAccount.setNewNum(mAccountManager.getUserData(mAccounts[0],
				Params.PARAMS_NEW_MOBILE_NUMBER));

		String sex = mAccountManager.getUserData(mAccounts[0],
				Params.PARAMS_USER_SEX);
		if (sex != null) {
			int i = 0;
			if (sex.equals("0")) {
				i = 0;
			} else {
				i = 1;
			}
			cityAccount.setSex(i);
		}
		return cityAccount;
	}
	return null;
}
 
Example 15
Source File: BillingBinder.java    From aptoide-client with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Bundle getPurchases(int apiVersion, String packageName, String type, String continuationToken) throws RemoteException {
    Log.d("AptoideBillingService", "[getPurchases]: " + packageName + " " + type);

    final Bundle result = new Bundle();

    if (apiVersion < 3 || !(type.equals(ITEM_TYPE_INAPP) || type.equals(ITEM_TYPE_SUBS))) {
        result.putInt(RESPONSE_CODE, RESULT_DEVELOPER_ERROR);
        return result;
    }

    AccountManager accountManager = AccountManager.get(context);
    Account[] accounts = accountManager.getAccountsByType(Aptoide.getConfiguration().getAccountType());

    if(accounts.length == 0) {

        Log.d("AptoideBillingService", "BillingUnavailable: user not logged in");
        result.putStringArrayList(INAPP_PURCHASE_ITEM_LIST, new ArrayList<String>());
        result.putStringArrayList(INAPP_PURCHASE_DATA_LIST, new ArrayList<String>());
        result.putStringArrayList(INAPP_DATA_SIGNATURE_LIST, new ArrayList<String>());
        result.putInt(RESPONSE_CODE, RESULT_OK);

        return result;
    }

    try {
        String token = accountManager.blockingGetAuthToken(accounts[0], "Full access", true);

        if(token != null) {
            final CountDownLatch latch = new CountDownLatch(1);
            IabPurchasesRequest request = new IabPurchasesRequest();
            request.setApiVersion(Integer.toString(apiVersion));
            request.setPackageName(packageName);
            request.setType(type);
            request.setToken(token);

            manager.execute(request, packageName + "-getPurchases-"+type, DurationInMillis.ONE_SECOND*5, new RequestListener<IabPurchasesJson>() {
                @Override
                public void onRequestFailure(SpiceException spiceException) {
                    result.putInt(RESPONSE_CODE, RESULT_ERROR);
                    latch.countDown();
                }

                @Override
                public void onRequestSuccess(IabPurchasesJson response) {
                    if("OK".equals(response.getStatus())) {

                        ArrayList<String> purchaseItemList = (ArrayList<String>) response.getPublisher_response().getItemList();
                        ArrayList<String> purchaseSignatureList = (ArrayList<String>) response.getPublisher_response().getSignatureList();

                        ArrayList<String> purchaseDataList = new ArrayList<String>();
                        for(IabPurchasesJson.PublisherResponse.PurchaseDataObject purchase : response.getPublisher_response().getPurchaseDataList()) {
                            Log.d("AptoideBillingService", "Purchase: " + purchase.getJson());
                            purchaseDataList.add(purchase.getJson());
                        }

                        result.putStringArrayList(INAPP_PURCHASE_ITEM_LIST, purchaseItemList);
                        result.putStringArrayList(INAPP_PURCHASE_DATA_LIST, purchaseDataList);
                        result.putStringArrayList(INAPP_DATA_SIGNATURE_LIST, purchaseSignatureList);
                        if(response.getPublisher_response().getInapp_continuation_token() != null) {
                            result.putString(INAPP_CONTINUATION_TOKEN, response.getPublisher_response().getInapp_continuation_token());
                        }
                        result.putInt(RESPONSE_CODE, RESULT_OK);
                    } else {
                        result.putInt(RESPONSE_CODE, RESULT_DEVELOPER_ERROR);
                    }
                    latch.countDown();
                }
            });

            latch.await();

        }

    } catch (Exception e) {
        e.printStackTrace();
        result.putInt(RESPONSE_CODE, RESULT_ERROR);
    }
    return result;
}
 
Example 16
Source File: DeviceUtil.java    From haxsync with GNU General Public License v2.0 4 votes vote down vote up
public static boolean hasAccount(Context context){
	AccountManager am = AccountManager.get(context);
	return (am.getAccountsByType("org.mots.haxsync.account").length > 0);
}
 
Example 17
Source File: GoogleBackup.java    From haxsync with GNU General Public License v2.0 4 votes vote down vote up
protected Boolean doInBackground(Void... params){
	AccountManager am = AccountManager.get(parent);
	Account account = am.getAccountsByType(parent.getString(R.string.ACCOUNT_TYPE))[0];
	
	if (FacebookUtil.authorize(parent, account)){
		String selfID = FacebookUtil.getSelfID();
		if (selfID == null){
			return false;
		}
		String googleName = googleAcc.name;
		Uri rawContactUri = RawContacts.CONTENT_URI.buildUpon()
				.appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
				.appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type)
				.build();
		Uri googleUri = RawContacts.CONTENT_URI.buildUpon()
				.appendQueryParameter(RawContacts.ACCOUNT_NAME, googleName)
				.appendQueryParameter(RawContacts.ACCOUNT_TYPE, "com.google")
				.build();
		ContentResolver mContentResolver = parent.getContentResolver();
		Cursor c1 = mContentResolver.query(rawContactUri, new String[] { BaseColumns._ID, RawContacts.CONTACT_ID, RawContacts.DISPLAY_NAME_PRIMARY, RawContacts.SYNC1 }, null, null, null);
		while (c1.moveToNext()) {
			long contactID = c1.getLong(c1.getColumnIndex(RawContacts.CONTACT_ID));
			Cursor c2 = mContentResolver.query(googleUri, new String[] { BaseColumns._ID}, RawContacts.CONTACT_ID +" = '" + contactID + "'", null, null);
			if (c2.getCount() > 0){
				c2.moveToFirst();
				contactName = c1.getString(c1.getColumnIndex(RawContacts.DISPLAY_NAME_PRIMARY));
				writeHTCData(c2.getLong(c2.getColumnIndex(BaseColumns._ID)), selfID, c1.getString(c1.getColumnIndex(RawContacts.SYNC1)));
				publishProgress((int) ((c1.getPosition() / (float) c1.getCount()) * 100));
	
			}
			c2.close();
			//Log.i("backup", );
			
		}
		c1.close();
		ContentResolver.requestSync(googleAcc, ContactsContract.AUTHORITY, new Bundle());
		return true;
	}
	else{
		return false;
	}
}
 
Example 18
Source File: AuthenticationUtil.java    From palmsuda with Apache License 2.0 4 votes vote down vote up
public synchronized static void saveNewAccount(Context context) {

		if (mAccount == null) {
			Log.e(TAG, "saveNewAccount: mAccount is empty!");
			return;
		}
		AccountManager mAccountManager = AccountManager.get(context);
		Account[] mAccounts = mAccountManager
				.getAccountsByType(Constants.ACCOUNT_TYPE);

		Log.d("hand", "-----mAccounts.length is: " + mAccounts.length
				+ "------------");

		if (mAccounts.length > 0) {
			Log.d(
					"hand",
					"saveNewAccount: account exist:"
							+ mAccount.getAccountName());
			return;
		}
		final Account account = new Account(
				context.getString(R.string.app_name), Constants.ACCOUNT_TYPE);
		Bundle userData = new Bundle();
		//userData.putInt(Params.PARAMS_ACCOUNT_TYPE, mAccount.type);
		userData.putString(Params.PARAMS_ACCOUNT_TYPE, "" + mAccount.type);

		userData.putString(Params.PARAMS_LOGIN_ID, mAccount.getAccountName());
		userData.putString(Params.PARAMS_LOGIN_PW, mAccount.getPassword());

		userData.putString(Params.PARAMS_USER_NICK_NAME, mAccount.getNickname());
		userData.putString(Params.PARAMS_USER_BIRTHDAY, mAccount.getBirthDate());
		userData.putString(Params.PARAMS_USER_CITY, mAccount.getCityName());
		userData.putString(Params.PARAMS_USER_DESC, mAccount.getMkeywords());
		//userData.putInt(Params.PARAMS_USER_SEX, mAccount.getSex());
		userData.putString(Params.PARAMS_USER_SEX, "" + mAccount.getSex());

		userData.putString(Params.PARAMS_USER_EMAIL, mAccount.getEmail());
		userData.putString(Params.PARAMS_NEW_MOBILE_NUMBER,
				mAccount.getNewNum());
		userData.putString(Params.PARAMS_LOGIN_IMSI, mAccount.getImsi());

		boolean addAccountSuccess = mAccountManager.addAccountExplicitly(
				account, mAccount.getAccountName(), userData);
		
		Log.d("hand", "--------addAccountSuccess is: " + addAccountSuccess + "-----------");
	}
 
Example 19
Source File: FragmentGmail.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
private void onAccountSelected(Intent data) {
    String name = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
    String type = data.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE);

    boolean found = false;
    AccountManager am = AccountManager.get(getContext());
    Account[] accounts = am.getAccountsByType(type);
    for (final Account account : accounts)
        if (name.equalsIgnoreCase(account.name)) {
            found = true;
            Log.i("Requesting token name=" + account.name);
            am.getAuthToken(
                    account,
                    EmailService.getAuthTokenType(type),
                    new Bundle(),
                    getActivity(),
                    new AccountManagerCallback<Bundle>() {
                        @Override
                        public void run(AccountManagerFuture<Bundle> future) {
                            try {
                                Bundle bundle = future.getResult();
                                String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                                if (token == null)
                                    throw new IllegalArgumentException("no token");
                                Log.i("Got token name=" + account.name);

                                onAuthorized(name, token);
                            } catch (Throwable ex) {
                                Log.e(ex);
                                tvError.setText(Log.formatThrowable(ex));
                                grpError.setVisibility(View.VISIBLE);

                                new Handler().post(new Runnable() {
                                    @Override
                                    public void run() {
                                        scroll.smoothScrollTo(0, tvError.getBottom());
                                    }
                                });
                            }
                        }
                    },
                    null);
            break;
        }

    if (!found) {
        boolean permission = Helper.hasPermission(getContext(), Manifest.permission.GET_ACCOUNTS);

        Map<String, String> crumb = new HashMap<>();
        crumb.put("type", type);
        crumb.put("count", Integer.toString(accounts.length));
        crumb.put("permission", Boolean.toString(permission));
        Log.breadcrumb("Gmail", crumb);

        Log.e("Account missing");

        tvError.setText(getString(R.string.title_no_account));
        grpError.setVisibility(View.VISIBLE);
    }
}
 
Example 20
Source File: BaseActivity.java    From attendee-checkin with Apache License 2.0 4 votes vote down vote up
private Account[] getAccounts() {
    AccountManager accountManager = AccountManager.get(getApplicationContext());
    return accountManager.getAccountsByType("com.google");
}