Example usage for android.accounts Account Account

List of usage examples for android.accounts Account Account

Introduction

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

Prototype

public Account(@NonNull Account other, @NonNull String accessId) 

Source Link

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;//from  ww  w.  j a v a 2  s.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:org.enbyted.android.zseinfo.view.activity.MainActivity.java

public static Account createSyncAccount(Context context) {
    Account newAccount = new Account(ACCOUNT, ACCOUNT_TYPE);
    AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE);

    if (accountManager.addAccountExplicitly(newAccount, null, null)) {
        ContentResolver.setSyncAutomatically(newAccount, AUTHORITY, true);
        ContentResolver.setIsSyncable(newAccount, AUTHORITY, 1);
    } else {/*  w  w w  .j  a  v  a 2s .c om*/

    }
    return newAccount;
}

From source file:com.ravi.apps.android.newsbytes.sync.NewsSyncAdapter.java

/**
 * Gets the fictitious account to be used with the sync adapter, or makes a new one
 * if the fictitious account doesn't exist yet.  If we make a new account, we call the
 * onAccountCreated method so we can initialize things.
 *//*from   w ww  . j a  v  a2  s.c  o  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.
    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. Add the account.
    if (null == accountManager.getPassword(newAccount)) {
        // Add the account and account type, no password or user data.
        if (!accountManager.addAccountExplicitly(newAccount, "", null)) {
            return null;
        }

        onAccountCreated(newAccount, context);
    }
    return newAccount;
}

From source file:jp.januaraid.android.synciteasy.gcm.GCMIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();/*from  w w  w  .j  a  v  a  2s  .  c om*/
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) { // has effect of unparcelling Bundle
        /*
         * Filter messages based on message type. Since it is likely that
         * GCM will be extended in the future with new message types, just
         * ignore any message types you're not interested in, or that you
         * don't recognize.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            Log.i(Consts.TAG, "onHandleIntent: message error");
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            Log.i(Consts.TAG, "onHandleIntent: message deleted");
            // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            String subId = intent.getStringExtra(GCM_KEY_SUBID);
            Log.i(Consts.TAG, "onHandleIntent: subId: " + subId);
            String[] tokens = subId.split(":");
            String typeId = tokens[1];

            // dispatch message
            if (GCM_TYPEID_QUERY.equals(typeId)) {
                Intent messageIntent = new Intent(BROADCAST_ON_MESSAGE);
                messageIntent.putExtras(intent);
                messageIntent.putExtra("token", tokens[2]);
                LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
                Log.i(Consts.TAG, ":sendBroadcast");
                // 
                String accountName = getApplicationContext()
                        .getSharedPreferences(Consts.PREF_KEY_CLOUD_BACKEND, Context.MODE_PRIVATE)
                        .getString(Consts.PREF_KEY_ACCOUNT_NAME, null);
                Account account = null;
                if (accountName == null) {
                    return;
                } else {
                    account = new Account(accountName, Consts.ACCOUNT_TYPE);
                }
                Bundle settingsBundle = new Bundle();
                settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
                settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
                settingsBundle.putString("token", tokens[2]);
                ContentResolver.requestSync(account, Consts.AUTHORITY, settingsBundle);
            }
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GCMBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:dev.drsoran.moloko.auth.AuthenticatorActivity.java

/**
 * Response is received from the server for authentication request. Sets the AccountAuthenticatorResult which is sent
 * back to the caller. Also sets the authToken in AccountManager for this account.
 *///from   ww  w .jav a 2s .co m
@Override
public void onAuthenticationFinished(RtmAuth rtmAuth) {
    final Account account = new Account(rtmAuth.getUser().getUsername(), Constants.ACCOUNT_TYPE);
    try {
        boolean ok = true;

        if (isNewAccount) {
            ok = accountManager.addAccountExplicitly(account, rtmAuth.getToken(), null);
            if (ok) {
                ContentResolver.setSyncAutomatically(account, Rtm.AUTHORITY, true);
            }
        }

        if (ok) {
            accountManager.setUserData(account, Constants.FEAT_API_KEY, MolokoApp.getRtmApiKey(this));
            accountManager.setUserData(account, Constants.FEAT_SHARED_SECRET,
                    MolokoApp.getRtmSharedSecret(this));
            accountManager.setUserData(account, Constants.FEAT_PERMISSION, rtmAuth.getPerms().toString());
            accountManager.setUserData(account, Constants.ACCOUNT_USER_ID, rtmAuth.getUser().getId());
            accountManager.setUserData(account, Constants.ACCOUNT_FULLNAME, rtmAuth.getUser().getFullname());

            final Intent intent = new Intent();

            intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, rtmAuth.getUser().getUsername());
            // We store the authToken as password
            intent.putExtra(AccountManager.KEY_PASSWORD, rtmAuth.getToken());
            intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
            intent.putExtra(AccountManager.KEY_AUTHTOKEN, rtmAuth.getToken());

            intent.putExtra(AccountManager.KEY_BOOLEAN_RESULT, true);

            setAccountAuthenticatorResult(intent.getExtras());
            setResult(RESULT_OK, intent);
        }
    } catch (SecurityException e) {
        MolokoApp.Log.e(getClass(), e.getLocalizedMessage());
        onAuthenticationFailed(getString(R.string.auth_err_cause_scurity));
    } finally {
        finish();
    }
}

From source file:fi.iki.murgo.irssinotifier.Server.java

private String generateToken(String accountName)
        throws OperationCanceledException, AuthenticatorException, IOException {
    UserHelper uf = new UserHelper();
    return uf.getAuthToken(activity, new Account(accountName, UserHelper.ACCOUNT_TYPE));
}

From source file:com.ntsync.android.sync.activities.CreatePwdProgressDialog.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AccountManager accountManager = AccountManager.get(getActivity());
    Bundle args = getArguments();//from www .  j  ava 2s . c  o  m
    String mUsername = args.getString(KeyPasswordActivity.PARAM_USERNAME);
    byte[] pwdSalt = args.getByteArray(KeyPasswordActivity.PARAM_SALT);
    Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);

    String pwd = args.getString(PARAM_PWD);
    byte[] pwdCheck = args.getByteArray(KeyPasswordActivity.PARAM_CHECK);

    // Retain to keep Task during conf changes
    setRetainInstance(true);
    setCancelable(false);

    if (pwd == null) {
        createTask = new CreatePwdTask(account, accountManager, pwdSalt);
    } else {
        createTask = new RecreateKeyTask(account, accountManager, pwdSalt, pwdCheck, pwd);
    }
    createTask.execute();
}

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

@Override
public String getAuthToken(final Activity activity, String inAuthority)
        throws OperationCanceledException, AuthenticatorException, IOException {
    final String authority = inAuthority == null ? Constants.AUTHORITY_DEFAULT : inAuthority;
    final AccountManager am = AccountManager.get(activity);
    String token = am.peekAuthToken(
            new Account(Constants.getAccountName(activity), Constants.getAccountType(activity)), authority);
    if (token == null) {
        final Account a = new Account(Constants.getAccountName(activity), Constants.getAccountType(activity));
        Account[] accounts = am.getAccountsByType(Constants.getAccountType(activity));
        if (accounts == null || accounts.length == 0) {
            am.addAccount(Constants.getAccountType(activity), authority, null, null, null,
                    new Callback(authority, activity), null);
        } else {//from   w  ww.j  a  va 2s .  c  o  m
            am.getAuthToken(a, authority, null, null, new Callback(authority, activity), null);
        }
        return null;
    }
    return token;

}

From source file:com.kinvey.sample.signin.GoogleLoginActivity.java

private void finishLogin(String authToken, String password) {
    final Account account = new Account(authToken, UserLogin.ACCOUNT_TYPE);
    Bundle userData = new Bundle();
    userData.putString(UserLogin.LOGIN_TYPE_KEY, PARAM_LOGIN_TYPE_GOOGLE);
    mAccountManager.addAccountExplicitly(account, password, userData);

    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, authToken);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, UserLogin.ACCOUNT_TYPE);
    setResult(RESULT_OK, intent);/*from  w w  w .  j a v a2 s .  c  o  m*/
    finish();
}

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 .  ja  va 2s .  c o  m
    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;
}