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

The following examples show how to use android.accounts.AccountManager#addAccountExplicitly() . 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: TestUtils.java    From indigenous-android with GNU General Public License v3.0 6 votes vote down vote up
static void createAccount(Context context, boolean microsub) {
    String domain = "http://example.com";
    String accessToken = "awesome";

    AccountManager am = AccountManager.get(context);
    Account account = new Account(domain, ACCOUNT_TYPE);
    am.addAccountExplicitly(account, null, null);
    am.setAuthToken(account, TOKEN_TYPE, accessToken);
    am.setUserData(account, "micropub_endpoint", domain + "/micropub");
    am.setUserData(account, "authorization_endpoint", domain + "/auth");
    am.setUserData(account, "micropub_media_endpoint", domain + "/media");
    am.setUserData(account, "token_endpoint", domain + "/token");
    am.setUserData(account, "author_name", "Indigenous");

    // Set first account.
    SharedPreferences.Editor editor = context.getSharedPreferences("indigenous", MODE_PRIVATE).edit();
    editor.putString("account", domain);
    editor.apply();
    editor.commit();
}
 
Example 2
Source File: Accounts.java    From cathode with Apache License 2.0 6 votes vote down vote up
public static void setupAccount(Context context) {
  AccountManager manager = AccountManager.get(context);

  Account account = getAccount(context);

  try {
    if (manager.addAccountExplicitly(account, null, null)) {
      ContentResolver.setIsSyncable(account, BuildConfig.AUTHORITY_DUMMY_CALENDAR, 1);
      ContentResolver.setSyncAutomatically(account, BuildConfig.AUTHORITY_DUMMY_CALENDAR, true);
      ContentResolver.addPeriodicSync(account, BuildConfig.AUTHORITY_DUMMY_CALENDAR, new Bundle(),
          12 * 60 * 60 /* 12 hours in seconds */);
    }
  } catch (SecurityException e) {
    Timber.e(e, "Unable to add account");
  }
}
 
Example 3
Source File: SyncUtils.java    From v2ex with Apache License 2.0 6 votes vote down vote up
/**
 * Create an entry for this application in the system account list, if it isn't already there.
 *
 * @param context Context
 */
public static void createSyncAccount(Context context) {

    // Create account, if it's missing. (Either first run, or user has deleted account.)
    Account account = AccountUtils.getActiveAccount(context);
    AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    accountManager.addAccountExplicitly(account, null, null);
    // Inform the system that this account supports sync
    ContentResolver.setIsSyncable(account, V2exContract.CONTENT_AUTHORITY, 1);
    // Inform the system that this account is eligible for auto sync when the network is up
    ContentResolver.setSyncAutomatically(account, V2exContract.CONTENT_AUTHORITY, true);

    Bundle extras = new Bundle();

    extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
    extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
    extras.putBoolean(SyncAdapter.EXTRA_SYNC_REMOTE, true);

    // Recommend a schedule for automatic synchronization. The system may modify this based
    // on other scheduled syncs and network utilization.
    ContentResolver.addPeriodicSync(
            account, V2exContract.CONTENT_AUTHORITY, extras, SYNC_FREQUENCY);
}
 
Example 4
Source File: LoginUtils.java    From android-galaxyzoo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Add the anonymous Account.
 *
 * Don't call this from the main thread - use an AsyncTask, for instance.
 * @param context
 */
private static void addAnonymousAccount(final Context context) {
    final AccountManager accountManager = AccountManager.get(context);
    final Account account = new Account(ACCOUNT_NAME_ANONYMOUS, LoginUtils.ACCOUNT_TYPE);
    //Note that this requires the AUTHENTICATE_ACCOUNTS permission on
    //SDK <=22:
    accountManager.addAccountExplicitly(account, null, null);

    //In case it has not been called yet.
    //This has no effect the second time.
    Utils.initDefaultPrefs(context);

    //Give the new account the existing (probably default) preferences,
    //so the SyncAdapter can use them.
    //See SettingsFragment.onSharedPreferenceChanged().
    copyPrefsToAccount(context, accountManager, account);

    //Tell the SyncAdapter to sync whenever the network is reconnected:
    setAutomaticAccountSync(context, account);
}
 
Example 5
Source File: AccountResolver.java    From RememBirthday with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Add account for Birthday Adapter to Android system
 */
public Bundle addAccountAndSync() {
    Log.d(getClass().getSimpleName(), "Adding calendar account : " + account.name);

    // enable automatic sync once per day
    ContentResolver.setSyncAutomatically(account, authority, true);
    ContentResolver.setIsSyncable(account, type, 1);

    // add periodic sync interval once per day
    long freq = AlarmManager.INTERVAL_DAY;
    ContentResolver.addPeriodicSync(account, type, new Bundle(), freq);

    AccountManager accountManager = AccountManager.get(context);
    if (accountManager.addAccountExplicitly(account, null, null)) {
        Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);

        // Force a sync! Even when background sync is disabled, this will force one sync!
        manualSync();

        return result;
    } else {
        return null;
    }
}
 
Example 6
Source File: SyncUtils.java    From ChannelSurfer with MIT License 6 votes vote down vote up
public static void setUpPeriodicSync(Context context, String inputId) {
        inputId = inputId==null?"":inputId;
        Account account = DummyAccountService.getAccount(context);
        AccountManager accountManager =
                (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
        if (!accountManager.addAccountExplicitly(account, null, null)) {
            Log.w(TAG, "Account already exists.");
//            return;
        }
        Log.d(TAG, "Set sync with "+inputId);
        ContentResolver.setIsSyncable(account, CONTENT_AUTHORITY, 1);
        ContentResolver.setSyncAutomatically(account, CONTENT_AUTHORITY, true);
        Bundle bundle = new Bundle();
        bundle.putString(SyncAdapter.BUNDLE_KEY_INPUT_ID, inputId);
        ContentResolver.addPeriodicSync(account, CONTENT_AUTHORITY, bundle,
                SyncAdapter.SYNC_FREQUENCY_SEC/6); //Sync every hour b/c why not?
    }
 
Example 7
Source File: ContactsManager.java    From Linphone4Android with GNU General Public License v3.0 6 votes vote down vote up
public void initializeSyncAccount(Context context, ContentResolver contentResolver) {
	initializeContactManager(context, contentResolver);
	AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);

	Account[] accounts = accountManager.getAccountsByType(context.getPackageName());

	if (accounts != null && accounts.length == 0) {
		Account newAccount = new Account(context.getString(R.string.sync_account_name), context.getPackageName());
		try {
			accountManager.addAccountExplicitly(newAccount, null, null);
		} catch (Exception e) {
			Log.e(e);
		}
	}
	initializeContactManager(context, contentResolver);
}
 
Example 8
Source File: AccountHelper.java    From background-geolocation-android with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new dummy account for the sync adapter
 *
 * @param context The application context
 */
public static android.accounts.Account CreateSyncAccount(Context context, String accountName, String accountType) {
    Account account = new Account(accountName, accountType);
    // Get an instance of the Android account manager
    AccountManager accountManager =  (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    /*
     * Add the account and account type, no password or user data
     * If successful, return the Account object, otherwise report an error.
     */
    if (accountManager.addAccountExplicitly(account, null, null)) {
        /*
         * If you don't set android:syncable="true" in
         * in your <provider> element in the manifest,
         * then call context.setIsSyncable(account, AUTHORITY, 1)
         * here.
         */
    } else {
        /*
         * The account exists or some other error occurred. Log this, report it,
         * or handle it internally.
         */
    }
    return account;
}
 
Example 9
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 10
Source File: PredatorAccount.java    From Capstone-Project with MIT License 5 votes vote down vote up
/**
 * Add a new account to the device for this application, this account can either be either
 * contain a client token or user token.
 *
 * @param context       Current context of the application
 * @param accountName   Name of the account
 * @param accountType   Account type
 * @param authToken     Authentication token
 * @param authTokenType Type of the authentication token
 */
public static void addAccount(Context context,
                              String accountName,
                              String accountType,
                              String authToken,
                              String authTokenType) {
    Account account = new Account(accountName, accountType);
    AccountManager accountManager = AccountManager.get(context);

    // Add a new account.
    accountManager.addAccountExplicitly(account, null, null);

    // Set the authentication code.
    accountManager.setAuthToken(account, authTokenType, authToken);
}
 
Example 11
Source File: SyncUtils.java    From android-BasicSyncAdapter with Apache License 2.0 5 votes vote down vote up
/**
 * Create an entry for this application in the system account list, if it isn't already there.
 *
 * @param context Context
 */
@TargetApi(Build.VERSION_CODES.FROYO)
public static void CreateSyncAccount(Context context) {
    boolean newAccount = false;
    boolean setupComplete = PreferenceManager
            .getDefaultSharedPreferences(context).getBoolean(PREF_SETUP_COMPLETE, false);

    // Create account, if it's missing. (Either first run, or user has deleted account.)
    Account account = GenericAccountService.GetAccount(ACCOUNT_TYPE);
    AccountManager accountManager =
            (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    if (accountManager.addAccountExplicitly(account, null, null)) {
        // Inform the system that this account supports sync
        ContentResolver.setIsSyncable(account, CONTENT_AUTHORITY, 1);
        // Inform the system that this account is eligible for auto sync when the network is up
        ContentResolver.setSyncAutomatically(account, CONTENT_AUTHORITY, true);
        // Recommend a schedule for automatic synchronization. The system may modify this based
        // on other scheduled syncs and network utilization.
        ContentResolver.addPeriodicSync(
                account, CONTENT_AUTHORITY, new Bundle(),SYNC_FREQUENCY);
        newAccount = true;
    }

    // Schedule an initial sync if we detect problems with either our account or our local
    // data has been deleted. (Note that it's possible to clear app data WITHOUT affecting
    // the account list, so wee need to check both.)
    if (newAccount || !setupComplete) {
        TriggerRefresh();
        PreferenceManager.getDefaultSharedPreferences(context).edit()
                .putBoolean(PREF_SETUP_COMPLETE, true).commit();
    }
}
 
Example 12
Source File: OdooAccountManager.java    From hr with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates Odoo account for app
 *
 * @param context
 * @param user    user instance (OUser)
 * @return true, if account created successfully
 */

public static boolean createAccount(Context context, OUser user) {
    AccountManager accountManager = AccountManager.get(context);
    Account account = new Account(user.getAndroidName(), KEY_ACCOUNT_TYPE);
    if (accountManager.addAccountExplicitly(account, String.valueOf(user.getPassword()),
            user.getAsBundle())) {
        OPreferenceManager pref = new OPreferenceManager(context);
        if (pref.getInt(userObjectKEY(user), 0) != OUser.USER_ACCOUNT_VERSION) {
            pref.putInt(userObjectKEY(user), OUser.USER_ACCOUNT_VERSION);
        }
        return true;
    }
    return false;
}
 
Example 13
Source File: UiUtils.java    From tindroid with Apache License 2.0 5 votes vote down vote up
static void updateAndroidAccount(final Context context, final String uid, final String secret,
                                 final String token, final Date tokenExpires) {
    final AccountManager am = AccountManager.get(context);
    final Account acc = Utils.createAccount(uid);
    // It's OK to call even if the account already exists.
    am.addAccountExplicitly(acc, secret, null);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        am.notifyAccountAuthenticated(acc);
    }
    if (!TextUtils.isEmpty(token)) {
        am.setAuthToken(acc, Utils.TOKEN_TYPE, token);
        am.setUserData(acc, Utils.TOKEN_EXPIRATION_TIME, String.valueOf(tokenExpires.getTime()));
    }
}
 
Example 14
Source File: SunshineSyncAdapter.java    From Krishi-Seva with MIT License 5 votes vote down vote up
/**
 * Helper method to get the fake account to be used with SyncAdapter, or make a new one
 * if the fake account doesn't exist yet.  If we make a new account, we call the
 * onAccountCreated method so we can initialize things.
 *
 * @param context The context used to access the account service
 * @return a fake account.
 */
public static Account getSyncAccount(Context context) {
    // Get an instance of the Android account manager
    AccountManager accountManager =
            (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);

    // Create the account type and default account
    Account newAccount = new Account(
            context.getString(R.string.app_name), context.getString(R.string.sync_account_type));

    // If the password doesn't exist, the account doesn't exist
    if ( null == accountManager.getPassword(newAccount) ) {

    /*
     * Add the account and account type, no password or user data
     * If successful, return the Account object, otherwise report an error.
     */
        if (!accountManager.addAccountExplicitly(newAccount, "", null)) {
            return null;
        }
        /*
         * If you don't set android:syncable="true" in
         * in your <provider> element in the manifest,
         * then call ContentResolver.setIsSyncable(account, AUTHORITY, 1)
         * here.
         */

        onAccountCreated(newAccount, context);
    }
    return newAccount;
}
 
Example 15
Source File: SyncAdapter.java    From react-native-sync-adapter with MIT License 5 votes vote down vote up
static Account getSyncAccount(Context context, int syncInterval, int syncFlexTime) {
    // Get an instance of the Android account manager
    AccountManager accountManager =
            (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);

    // Create the account type and default account
    Account newAccount = new Account(context.getString(R.string.app_name),
            context.getString(R.string.rnsb_sync_account_type));

    // If the password doesn't exist, the account doesn't exist
    if (null == accountManager.getPassword(newAccount)) {

    /*
     * Add the account and account type, no password or user data
     * If successful, return the Account object, otherwise report an error.
     */
        if (!accountManager.addAccountExplicitly(newAccount, "", null)) {
            return null;
        }
        /*
         * If you don't set android:syncable="true" in
         * in your <provider> element in the manifest,
         * then call ContentResolver.setIsSyncable(account, AUTHORITY, 1)
         * here.
         */
        onAccountCreated(newAccount, context, syncInterval, syncFlexTime);
    }
    return newAccount;
}
 
Example 16
Source File: AccountAuthenticator.java    From cathode with Apache License 2.0 5 votes vote down vote up
@Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType,
    String authTokenType, String[] requiredFeatures, Bundle options)
    throws NetworkErrorException {
  AccountManager manager = AccountManager.get(context);

  final Account account =
      new Account(context.getString(R.string.accountName), context.getPackageName());
  manager.addAccountExplicitly(account, null, null);

  return null;
}
 
Example 17
Source File: OdooAccountManager.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates Odoo account for app
 *
 * @param context
 * @param user    user instance (OUser)
 * @return true, if account created successfully
 */

public static boolean createAccount(Context context, OUser user) {
    AccountManager accountManager = AccountManager.get(context);
    Account account = new Account(user.getAndroidName(), KEY_ACCOUNT_TYPE);
    if (accountManager.addAccountExplicitly(account, String.valueOf(user.getPassword()),
            user.getAsBundle())) {
        OPreferenceManager pref = new OPreferenceManager(context);
        if (pref.getInt(userObjectKEY(user), 0) != OUser.USER_ACCOUNT_VERSION) {
            pref.putInt(userObjectKEY(user), OUser.USER_ACCOUNT_VERSION);
        }
        return true;
    }
    return false;
}
 
Example 18
Source File: ContactsManager.java    From linphone-android with GNU General Public License v3.0 5 votes vote down vote up
private void initializeSyncAccount() {
    AccountManager accountManager =
            (AccountManager) mContext.getSystemService(Context.ACCOUNT_SERVICE);

    Account[] accounts =
            accountManager.getAccountsByType(mContext.getString(R.string.sync_account_type));

    if (accounts != null && accounts.length == 0) {
        Account newAccount =
                new Account(
                        mContext.getString(R.string.sync_account_name),
                        mContext.getString(R.string.sync_account_type));
        try {
            accountManager.addAccountExplicitly(newAccount, null, null);
            Log.i("[Contacts Manager] Contact account added");
            makeContactAccountVisible();
        } catch (Exception e) {
            Log.e("[Contacts Manager] Couldn't initialize sync account: " + e);
        }
    } else if (accounts != null) {
        for (Account account : accounts) {
            Log.i(
                    "[Contacts Manager] Found account with name \""
                            + account.name
                            + "\" and type \""
                            + account.type
                            + "\"");
            makeContactAccountVisible();
        }
    }
}
 
Example 19
Source File: AuthenticationActivity.java    From Mover with Apache License 2.0 5 votes vote down vote up
@Subscribe
public void onEvent(AuthenticationEvent event){
    Bundle result = event.getResult();
    setLockForm(false);

    if(event.isSuccess()){
        String password = mPasswordField.getText().toString();
        AccountManager manager = AccountManager.get(this);

        Bundle userData = new Bundle();
        userData.putString(USER_PICTURE_URL, result.getString(USER_PICTURE_URL));

        manager.addAccountExplicitly(mAccount, password, userData);
        manager.setAuthToken(mAccount, mSourceId, result.getString(KEY_AUTHTOKEN));

        mAuthenticatorResponse.onResult(result);
        mAuthenticatorResponse = null;

        setResult(RESULT_OK);
        finish();

    }else{
        int errorCode = result.getInt(KEY_ERROR_CODE);

        if(errorCode == ERROR_CODE_INVALID_USER_DATA){
            mUsernameField.setError(getString(R.string.sign_in_failed_with_wrong_data_username));
            mPasswordField.setError(getString(R.string.sign_in_failed_with_wrong_data_password));
        }
    }
}
 
Example 20
Source File: SyncHelper.java    From v2ex with Apache License 2.0 4 votes vote down vote up
public static void requestManualSync(Context context, Bundle args) {
    Account account = AccountUtils.getActiveAccount(context);
    if (account != null) {
        LOGD(TAG, "Requesting manual sync for account " + account.name
                +" args=" + args.toString());

        args.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        args.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
        args.putBoolean(SyncAdapter.EXTRA_SYNC_REMOTE, false);

        AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
        accountManager.addAccountExplicitly(account, null, null);

        // Inform the system that this account is eligible for auto sync when the network is up
        ContentResolver.setSyncAutomatically(account, V2exContract.CONTENT_AUTHORITY, true);

        // Inform the system that this account supports sync
        ContentResolver.setIsSyncable(account, V2exContract.CONTENT_AUTHORITY, 1);

        boolean pending = ContentResolver.isSyncPending(account,
                V2exContract.CONTENT_AUTHORITY);
        if (pending) {
            LOGD(TAG, "Warning: sync is PENDING. Will cancel.");
        }
        boolean active = ContentResolver.isSyncActive(account,
                V2exContract.CONTENT_AUTHORITY);
        if (active) {
            LOGD(TAG, "Warning: sync is ACTIVE. Will cancel.");
        }

        if (pending || active) {
            LOGD(TAG, "Cancelling previously pending/active sync.");
            ContentResolver.cancelSync(account, V2exContract.CONTENT_AUTHORITY);
        }

        LOGD(TAG, "Requesting sync now.");
        ContentResolver.requestSync(account, V2exContract.CONTENT_AUTHORITY, args);
    } else {
        LOGD(TAG, "Can't request manual sync -- no chosen account.");
    }
}