Example usage for android.accounts AccountManager addAccountExplicitly

List of usage examples for android.accounts AccountManager addAccountExplicitly

Introduction

In this page you can find the example usage for android.accounts AccountManager addAccountExplicitly.

Prototype

public boolean addAccountExplicitly(Account account, String password, Bundle userdata) 

Source Link

Document

Adds an account directly to the AccountManager.

Usage

From source file:me.philio.ghost.ui.LoginActivity.java

@Override
public void onSuccess(String email, String password, Token token, User user) {
    // Create the account
    Account account = new Account(AccountUtils.getName(mBlogUrl, email), getString(R.string.account_type));
    Bundle userdata = new Bundle();
    userdata.putString(KEY_BLOG_URL, mBlogUrl);
    userdata.putString(KEY_EMAIL, email);
    userdata.putString(KEY_ACCESS_TOKEN_TYPE, token.tokenType);
    userdata.putString(KEY_ACCESS_TOKEN_EXPIRES,
            Long.toString(System.currentTimeMillis() + (token.expires * 1000)));

    // Add account to the system
    AccountManager accountManager = AccountManager.get(this);
    accountManager.addAccountExplicitly(account, password, userdata);

    // Set the account auth tokens
    accountManager.setAuthToken(account, TOKEN_TYPE_ACCESS, token.accessToken);
    accountManager.setAuthToken(account, TOKEN_TYPE_REFRESH, token.refreshToken);

    // Create initial database records
    Blog blog = new Blog();
    blog.url = mBlogUrl;/* w  w w . j a  v a  2s  .  c o  m*/
    blog.email = email;
    user.blog = blog;
    ActiveAndroid.beginTransaction();
    try {
        blog.save();
        user.save();
        ActiveAndroid.setTransactionSuccessful();
    } finally {
        ActiveAndroid.endTransaction();
    }

    // Enable sync for the account
    ContentResolver.setSyncAutomatically(account, getString(R.string.content_authority), true);
    SyncHelper.requestSync(account, getString(R.string.content_authority));

    // Set response intent
    Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, account.type);
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

From source file:com.gaba.alex.trafficincidents.MainActivity.java

private Account createSyncAccount() {
    Account appAccount = new Account(mAccountName, mAccountType);
    AccountManager accountManager = AccountManager.get(this);
    if (accountManager.addAccountExplicitly(appAccount, null, null)) {
        ContentResolver.setMasterSyncAutomatically(true);
        ContentResolver.setSyncAutomatically(appAccount, AUTHORITY, true);
    }//from  ww  w  . j  a v  a2 s .c om
    return appAccount;
}

From source file:io.v.android.apps.account_manager.AccountActivity.java

private void enforceAccountExists() {
    if (AccountManager.get(this).getAccountsByType(Constants.ACCOUNT_TYPE).length <= 0) {
        String name = "Vanadium";
        Account account = new Account(name, getResources().getString(R.string.authenticator_account_type));
        AccountManager am = AccountManager.get(this);
        am.addAccountExplicitly(account, null, null);
    }/*from w w w.j a v  a  2  s. c o  m*/
}

From source file:at.bitfire.davdroid.ui.setup.AccountDetailsFragment.java

protected boolean createAccount(String accountName, DavResourceFinder.Configuration config) {
    Account account = new Account(accountName, Constants.ACCOUNT_TYPE);

    // create Android account
    Bundle userData = AccountSettings.initialUserData(config.userName);
    App.log.log(Level.INFO, "Creating Android account with initial config", new Object[] { account, userData });

    AccountManager accountManager = AccountManager.get(getContext());
    if (!accountManager.addAccountExplicitly(account, config.password, userData))
        return false;

    // add entries for account to service DB
    App.log.log(Level.INFO, "Writing account configuration to database", config);
    @Cleanup//from w  w w .  j a v a2  s  .c om
    OpenHelper dbHelper = new OpenHelper(getContext());
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    try {
        AccountSettings settings = new AccountSettings(getContext(), account);

        Intent refreshIntent = new Intent(getActivity(), DavService.class);
        refreshIntent.setAction(DavService.ACTION_REFRESH_COLLECTIONS);

        if (config.cardDAV != null) {
            // insert CardDAV service
            long id = insertService(db, accountName, Services.SERVICE_CARDDAV, config.cardDAV);

            // start CardDAV service detection (refresh collections)
            refreshIntent.putExtra(DavService.EXTRA_DAV_SERVICE_ID, id);
            getActivity().startService(refreshIntent);

            // initial CardDAV account settings
            int idx = spnrGroupMethod.getSelectedItemPosition();
            String groupMethodName = getResources()
                    .getStringArray(R.array.settings_contact_group_method_values)[idx];
            settings.setGroupMethod(GroupMethod.valueOf(groupMethodName));

            // enable contact sync
            ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1);
            settings.setSyncInterval(ContactsContract.AUTHORITY, DEFAULT_SYNC_INTERVAL);
        } else
            // disable contact sync when CardDAV is not available
            ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0);

        if (config.calDAV != null) {
            // insert CalDAV service
            long id = insertService(db, accountName, Services.SERVICE_CALDAV, config.calDAV);

            // start CalDAV service detection (refresh collections)
            refreshIntent.putExtra(DavService.EXTRA_DAV_SERVICE_ID, id);
            getActivity().startService(refreshIntent);

            // enable calendar sync
            ContentResolver.setIsSyncable(account, CalendarContract.AUTHORITY, 1);
            settings.setSyncInterval(CalendarContract.AUTHORITY, DEFAULT_SYNC_INTERVAL);

            // enable task sync, if possible
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                /* Android >=6, it's possible to gain OpenTasks permissions dynamically, so
                 * OpenTasks sync will be enabled by default. Setting the sync interval to "manually"
                 * if OpenTasks is not installed avoids the "sync error" in Android settings / Accounts. */
                ContentResolver.setIsSyncable(account, TaskProvider.ProviderName.OpenTasks.authority, 1);
                settings.setSyncInterval(TaskProvider.ProviderName.OpenTasks.authority,
                        LocalTaskList.tasksProviderAvailable(getContext()) ? DEFAULT_SYNC_INTERVAL
                                : AccountSettings.SYNC_INTERVAL_MANUALLY);
            } else {
                // Android <6: enable task sync according to whether OpenTasks is accessible
                if (LocalTaskList.tasksProviderAvailable(getContext())) {
                    ContentResolver.setIsSyncable(account, TaskProvider.ProviderName.OpenTasks.authority, 1);
                    settings.setSyncInterval(TaskProvider.ProviderName.OpenTasks.authority,
                            DEFAULT_SYNC_INTERVAL);
                } else
                    // Android <6 only: disable OpenTasks sync forever when OpenTasks is not installed
                    // because otherwise, there will be a non-catchable SecurityException as soon as OpenTasks is installed
                    ContentResolver.setIsSyncable(account, TaskProvider.ProviderName.OpenTasks.authority, 0);
            }
        } else {
            // disable calendar and task sync when CalDAV is not available
            ContentResolver.setIsSyncable(account, CalendarContract.AUTHORITY, 0);
            ContentResolver.setIsSyncable(account, TaskProvider.ProviderName.OpenTasks.authority, 0);
        }

    } catch (InvalidAccountException e) {
        App.log.log(Level.SEVERE, "Couldn't access account settings", e);
    }

    return true;
}

From source file:com.busticket.amedora.busticketsrl.TicketingHomeActivity.java

/**
 * Create a new dummy account for the sync adapter
 *
 * @param context The application context
 *///from  ww w. j av  a  2s.  co  m
public static Account CreateSyncAccount(Context context) {
    // Create the account type and default account
    Account newAccount = new Account(ACCOUNT, ACCOUNT_TYPE);
    // Get an instance of the Android account manager
    AccountManager accountManager = (AccountManager) context.getSystemService(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(newAccount, 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.
         */
        Log.d("SYNC ERR", "The account exists or some other error occurred. Log this, report it,");
    }
    return newAccount;
}

From source file:eu.trentorise.smartcampus.ac.authenticator.AMSCAccessProvider.java

private void storeAnonymousToken(final String token, final String authority, final AccountManager am,
        final Account a) {
    if (token == null)
        return;/*from  w  w w  . j  ava  2 s .com*/
    am.setAuthToken(a, authority, token);
    am.setAuthToken(a, Constants.TOKEN_TYPE_ANONYMOUS, token);
    am.addAccountExplicitly(a, null, null);
}

From source file:com.glandorf1.joe.wsprnetviewer.app.sync.WsprNetViewerSyncAdapter.java

/**
 * Create a new dummy account for the sync adapter
 *
 * @param context The application context
 *///from  w  ww  .  j  a  v  a 2  s . co  m
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
    // app_name = WsprNetViewer
    // sync_account_type = wsprnetviewer.joe.glandorf1.com
    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.
        boolean ret = accountManager.addAccountExplicitly(newAccount, "", null);
        if (!ret) {
            return 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.
        onAccountCreated(newAccount, context);
    }
    return newAccount;
}

From source file:org.amahi.anywhere.activity.AuthenticationActivity.java

private void finishAuthentication(String authenticationToken) {
    AccountManager accountManager = AccountManager.get(this);

    Bundle authenticationBundle = new Bundle();

    Account account = new AmahiAccount(getUsername());

    if (accountManager.addAccountExplicitly(account, getPassword(), null)) {
        authenticationBundle.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        authenticationBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        authenticationBundle.putString(AccountManager.KEY_AUTHTOKEN, authenticationToken);

        accountManager.setAuthToken(account, account.type, authenticationToken);
    }//w  w w. ja  v a  2  s. c  om

    setAccountAuthenticatorResult(authenticationBundle);

    setResult(Activity.RESULT_OK);

    finish();
}

From source file:com.hybris.mobile.app.commerce.CommerceApplicationBase.java

/**
 * Add a default account to the sync adapter
 *///from   ww w  . jav  a2  s .com
private void addCatalogSyncAdapterDefaultAccount() {
    AccountManager accountManager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
    accountManager.addAccountExplicitly(
            new Account(getString(R.string.account_name), getString(R.string.account_type)), null, null);
}

From source file:com.lambdasoup.watchlater.test.AddActivityTest.java

private void addAccount(Account account) {
    AccountManager accountManager = AccountManager
            .get(InstrumentationRegistry.getInstrumentation().getContext());
    //noinspection ResourceType
    accountManager.addAccountExplicitly(account, null, null);
}