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:edu.mit.mobile.android.locast.accounts.AuthenticatorActivity.java

/**
 *
 * Called when response is received from the server for authentication request. See
 * onAuthenticationResult(). Sets the AccountAuthenticatorResult which is sent back to the
 * caller. Also sets the authToken in AccountManager for this account.
 *
 * @param userData// w  w w . j ava 2 s . c  om
 *            TODO
 * @param the
 *            confirmCredentials result.
 */

protected void finishLogin(Bundle userData) {
    Log.i(TAG, "finishLogin()");
    // ensure that there isn't a demo account sticking around.

    // TODO this is NOT the place where this code belongs. Find it a better home
    if (Authenticator.isDemoMode(this)) {
        Log.d(TAG, "cleaning up demo mode account...");
        ContentResolver.cancelSync(Authenticator.getFirstAccount(this), MediaProvider.AUTHORITY);

        mAccountManager.removeAccount(
                new Account(Authenticator.DEMO_ACCOUNT, AuthenticationService.ACCOUNT_TYPE),
                new AccountManagerCallback<Boolean>() {

                    @Override
                    public void run(AccountManagerFuture<Boolean> arg0) {
                        try {
                            if (arg0.getResult()) {

                                final ContentValues cv = new ContentValues();
                                // invalidate all the content to force a sync.
                                // this is to ensure that items which were marked favorite get set as
                                // such.
                                cv.put(Cast._SERVER_MODIFIED_DATE, 0);
                                cv.put(Cast._MODIFIED_DATE, 0);
                                getContentResolver().update(Cast.CONTENT_URI, cv, null, null);
                                if (Constants.DEBUG) {
                                    Log.d(TAG, "reset all cast modified dates to force a reload");
                                }
                            }
                        } catch (final OperationCanceledException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (final AuthenticatorException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (final IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }, null);

    }
    final Account account = new Account(mUsername, AuthenticationService.ACCOUNT_TYPE);

    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, userData);
        // Automatically enable sync for this account
        ContentResolver.setSyncAutomatically(account, MediaProvider.AUTHORITY, true);
    } else {
        mAccountManager.setPassword(account, mPassword);
    }
    final Intent intent = new Intent();
    mAuthtoken = mPassword;
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AuthenticationService.ACCOUNT_TYPE);
    if (mAuthtokenType != null && mAuthtokenType.equals(AuthenticationService.AUTHTOKEN_TYPE)) {
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken);
    }
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

From source file:com.owncloud.android.services.observer.FileObserverService.java

/**
 * Read from the local database the list of files that must to be kept
 * synchronized and starts observers to monitor local changes on them.
 * /*from  www  .  j  a  v  a  2  s. c o  m*/
 * Updates the list of currently observed files if called multiple times.
 */
private void startObservation() {
    Log_OC.d(TAG, "Loading all available offline files from database to start watching them");
    FileDataStorageManager fds = new FileDataStorageManager(null, // this is dangerous - handle with care
            getContentResolver());

    List<Pair<OCFile, String>> availableOfflineFiles = fds.getAvailableOfflineFilesFromEveryAccount();
    OCFile file;
    String accountName;
    Account account;
    for (Pair<OCFile, String> pair : availableOfflineFiles) {
        file = pair.first;
        accountName = pair.second;
        account = new Account(accountName, MainApp.getAccountType());
        if (!AccountUtils.exists(account, this)) {
            continue;
        }
        addObservedFile(file, account);
    }

    // watch for instant uploads
    updateInstantUploadsObservers();

    // service does not stopSelf() ; that way it tries to be alive forever
}

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

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

/**
 * Request a sync of the catalog sync adapter
 *
 * @param bundle/*from   www  . j av a  2  s .  co  m*/
 */
public static void requestCatalogSyncAdapter(Bundle bundle) {
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    ContentResolver.requestSync(
            new Account(mInstance.getString(R.string.account_name), mInstance.getString(R.string.account_type)),
            mInstance.getString(R.string.provider_authority), bundle);
}

From source file:com.nbos.phonebook.sync.authenticator.AuthenticatorActivity.java

/**
 * Called when response is received from the server for confirm credentials
 * request. See onAuthenticationResult(). Sets the
 * AccountAuthenticatorResult which is sent back to the caller.
 * // w  w  w.ja  v a  2 s  .c o m
 * @param the confirmCredentials result.
 */
protected void finishConfirmCredentials(boolean result) {
    Log.i(tag, "finishConfirmCredentials()");
    final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);
    mAccountManager.setPassword(account, mPassword);
    mAccountManager.setUserData(account, Constants.PHONE_NUMBER_KEY, countryCode + mPhone);
    Db.deleteServerData(getApplicationContext());
    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_BOOLEAN_RESULT, result);
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

From source file:com.example.igorklimov.popularmoviesdemo.sync.SyncAdapter.java

/**
 * Create a new dummy account for the sync adapter
 *
 * @param context The application context
 *//*from w  ww. java 2 s.c om*/
public static Account getSyncAccount(Context context) {
    Account newAccount = new Account(context.getString(R.string.app_name),
            context.getString(R.string.acc_sync_type));
    AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);

    if (accountManager.getPassword(newAccount) == null) {
        if (!accountManager.addAccountExplicitly(newAccount, "", null))
            return null;

        onAccountCreated(newAccount, context);
    }

    return newAccount;
}

From source file:com.murrayc.galaxyzoo.app.LoginUtils.java

/** Don't call this from the main UI thread.
 *
 * @param context/*from   w  w  w.  java  2s .com*/
 */
public static void removeAccount(final Context context, final String accountName) {
    final AccountManager accountManager = AccountManager.get(context);
    final Account account = new Account(accountName, LoginUtils.ACCOUNT_TYPE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        //Trying to call this on an older Android version results in a
        //NoSuchMethodError exception.
        //There is no AppCompat version of the AccountManager API to
        //avoid the need for this version check at runtime.
        accountManager.removeAccount(account, null, null, null);
    } else {
        //noinspection deprecation
        //Note that this needs the MANAGE_ACCOUNT permission on
        //SDK <=22.
        //noinspection deprecation
        accountManager.removeAccount(account, null, null);
    }
}

From source file:com.sefford.beauthentic.activities.LoginActivity.java

void performLogin() {
    final AccountManager am = AccountManager.get(this);
    final Bundle data = new Bundle();
    data.putString(AuthenticAuthenticator.EXTRA_PASSWORD, etPassword.getText().toString());
    data.putInt(AuthenticAuthenticator.EXTRA_TYPE, AuthenticAuthenticator.Type.PASSWORD.ordinal());
    final Account account = new Account(etUsername.getText().toString(), AuthenticAuthenticator.ACCOUNT_TYPE);
    am.getAuthToken(account, "", data, true, new AccountManagerCallback<Bundle>() {
        @Override/*w w  w.j  a va 2s.co  m*/
        public void run(AccountManagerFuture<Bundle> future) {
            try {
                final Bundle result = future.getResult();
                if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)) {
                    Sessions.addAccount(am, account, etPassword.getText().toString(), Bundle.EMPTY);
                    am.setAuthToken(account, AuthenticAuthenticator.AUTHTOKEN_TYPE,
                            result.getString(AccountManager.KEY_AUTHTOKEN));
                    am.setUserData(account, AuthenticAuthenticator.EXTRA_TYPE,
                            Integer.toString(AuthenticAuthenticator.Type.PASSWORD.ordinal()));
                    notifyLoginToGCM(AuthenticAuthenticator.Type.PASSWORD.ordinal(), account.name,
                            etPassword.getText().toString(), result.getString(AccountManager.KEY_AUTHTOKEN));
                    googleApi
                            .saveCredential(
                                    new Credential.Builder(account.name)
                                            .setPassword(etPassword.getText().toString()).build(),
                                    new SmartlockCredentialCallback());
                } else {
                    Snackbar.make(vLoginForm, R.string.error_invalid_credentials, Snackbar.LENGTH_LONG).show();
                }
            } catch (OperationCanceledException e) {
                Snackbar.make(vLoginForm, R.string.error_operation_cancelled, Snackbar.LENGTH_LONG).show();
            } catch (IOException e) {
                Snackbar.make(vLoginForm, R.string.error_not_connected_to_internet, Snackbar.LENGTH_LONG)
                        .show();
            } catch (AuthenticatorException e) {
                Snackbar.make(vLoginForm, R.string.error_invalid_credentials, Snackbar.LENGTH_LONG).show();
            }
        }

    }, null);
}

From source file:org.voidsink.anewjkuapp.activity.KusssAuthenticatorActivity.java

private void finishLogin(Intent intent) {
    String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
    String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
    String accountType = intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE);

    Log.i(TAG, "finish login to " + accountName);

    Account account;/*from   w  w  w. jav  a2  s .  com*/
    boolean addNewAccount;

    final Account oldAccount = AppUtils.getAccount(this);
    if (oldAccount != null) {
        if (oldAccount.name.equals(accountName)) {
            account = oldAccount;
            addNewAccount = false;
        } else {
            AppUtils.removeAccout(mAccountManager, oldAccount);
            account = new Account(accountName, accountType);
            addNewAccount = true;
        }
    } else {
        account = new Account(accountName, accountType);
        addNewAccount = true;
    }

    if (addNewAccount) {
        String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
        String authtokenType = mAuthTokenType;

        // Creating the account on the device and setting the auth token we
        // got
        // (Not setting the auth token will cause another call to the server
        // to authenticate the user)
        mAccountManager.addAccountExplicitly(account, accountPassword, null);
        mAccountManager.setAuthToken(account, authtokenType, authtoken);
        mAccountManager.setPassword(account, accountPassword);

        // Turn on periodic syncing
        long interval = PreferenceWrapper.getSyncInterval(this) * 60 * 60;

        ContentResolver.addPeriodicSync(account, CalendarContractWrapper.AUTHORITY(), new Bundle(), interval);
        ContentResolver.addPeriodicSync(account, KusssContentContract.AUTHORITY, new Bundle(), interval);
        // Inform the system that this account supports sync
        ContentResolver.setIsSyncable(account, CalendarContractWrapper.AUTHORITY(), 1);
        ContentResolver.setIsSyncable(account, KusssContentContract.AUTHORITY, 1);
        // Inform the system that this account is eligible for auto sync
        // when the network is up
        ContentResolver.setSyncAutomatically(account, CalendarContractWrapper.AUTHORITY(), true);
        ContentResolver.setSyncAutomatically(account, KusssContentContract.AUTHORITY, true);
        // Recommend a schedule for automatic synchronization. The system
        // may modify this based
        // on other scheduled syncs and network utilization.
    } else {
        mAccountManager.setPassword(account, accountPassword);
    }

    // Kalender aktualisieren
    CalendarUtils.createCalendarsIfNecessary(this, account);

    // Sync NOW
    KusssAuthenticator.triggerSync(this);

    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);

    finish();
}

From source file:ch.scythe.hsr.TimeTableActivity.java

private synchronized void startRequest(Date date, boolean forceRequest) {

    Account account = AndroidHelper.getAccount(accountManager);

    persistCurrentTab();//from   w w  w  . ja  v  a  2s  .  co  m

    // try to migrate settings
    if (account == null) {
        SharedPreferences oldPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        String login = oldPrefs.getString(getString(R.string.key_login), null);
        String password = oldPrefs.getString(getString(R.string.key_password), null);

        if (!TextUtils.isEmpty(login) && !TextUtils.isEmpty(password)) {
            account = new Account(login.toLowerCase(), Constants.ACCOUNT_TYPE);
            accountManager.addAccountExplicitly(account, password, null);
            Toast.makeText(getApplicationContext(),
                    "Automatically migrated your HSR Login into the Android AccountManager.", Toast.LENGTH_LONG)
                    .show();
            Editor editor = oldPrefs.edit();
            editor.clear();
            editor.commit();
        }
    }

    if (account == null) {

        showDialog(DIALOG_NO_USER_PASS);
    } else if (api.retrieveRequiresBlockingCall(forceRequest)) { // TODO implement this
        progress = new ProgressDialog(this);
        progress.setMessage(getText(R.string.message_loading_data));
        progress.setIndeterminate(true);
        progress.setCancelable(true);
        progress.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                Log.i(LOGGING_TAG, "dialog cancel has been invoked");
                if (task != null) {
                    task.cancel(true);
                }
            }
        });
        progress.show();

        // progress = ProgressDialog.show(this, "", getString(R.string.message_loading_data));
        task = new FetchDataTask().execute(date, account, forceRequest);
    } else {
        task = new FetchDataTask().execute(date, account, forceRequest);
    }
}