Example usage for android.accounts AccountManager get

List of usage examples for android.accounts AccountManager get

Introduction

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

Prototype

public static AccountManager get(Context context) 

Source Link

Document

Gets an AccountManager instance associated with a Context.

Usage

From source file:com.google.android.gm.ay.java

public static void bf(final Context context) {
    final b dd = b.DD();
    final String bs = dd.bs(context);
    final android.accounts.Account[] accountsByType = AccountManager.get(context)
            .getAccountsByType("com.google");
    if (accountsByType.length > 0 && !bi(context)) {
        final String name = accountsByType[0].name;
        final Intent intent = new Intent();
        intent.setClass(context, (Class) ao.class);
        intent.putExtra("account-name", name);
        context.startService(intent);//from  ww w .  j a v  a2 s . co m
    }
    for (int length = accountsByType.length, i = 0; i < length; ++i) {
        if (accountsByType[i].name.equals(bs)) {
            return;
        }
    }
    if (accountsByType.length > 0) {
        dd.z(context, accountsByType[0].name);
    }
}

From source file:com.xiaomi.account.utils.SysHelper.java

public static XiaomiUserInfo queryXiaomiUserInfo(Context context, Account account) {
    XiaomiUserInfo xiaomiUserInfo = null;
    if (account != null) {
        String userId = account.name;
        AccountManager am = AccountManager.get(context);
        int count = 0;
        while (count < 2) {
            String authToken = getAuthToken(am, account, Constants.PASSPORT_API_SID);
            ExtendedAuthToken extendedAuthToken = ExtendedAuthToken.parse(authToken);
            if (extendedAuthToken == null) {
                break;
            }/*from  ww  w .  j av  a 2  s.c  o  m*/
            String serviceToken = extendedAuthToken.authToken;
            String security = extendedAuthToken.security;
            if (serviceToken == null || security == null) {
                break;
            }
            try {
                xiaomiUserInfo = CloudHelper.getXiaomiUserInfo(userId,
                        am.getUserData(account, Constants.KEY_ENCRYPTED_USER_ID), serviceToken, security);
                break;
            } catch (InvalidResponseException e) {
                Log.e(TAG, "invalid response when get user info", e);
            } catch (CipherException e2) {
                Log.e(TAG, "CipherException when get user info", e2);
            } catch (IOException e3) {
                Log.e(TAG, "IOException when get user info", e3);
            } catch (AuthenticationFailureException e4) {
                Log.e(TAG, "auth failure when get user info", e4);
                am.invalidateAuthToken(account.type, authToken);
                count++;
            } catch (AccessDeniedException e5) {
                Log.e(TAG, "access denied when get user info", e5);
            }
        }
    } else {
        Log.w(TAG, "no Xiaomi account, skip to query user info");
    }
    return xiaomiUserInfo;
}

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

@Override
public boolean isUserAnonymous(Context ctx) {
    AccountManager am = AccountManager.get(ctx);
    Account account = new Account(Constants.getAccountName(ctx), Constants.getAccountType(ctx));
    String authority = am.getUserData(account, Constants.KEY_AUTHORITY);
    return Constants.TOKEN_TYPE_ANONYMOUS.equals(authority);
}

From source file:com.example.am.myapplication.ContactAdder.java

/**
 * Called when this activity is about to be destroyed by the system.
 *///from  www  .j  a va  2s.c  om
@Override
public void onDestroy() {
    // Remove AccountManager callback
    AccountManager.get(this).removeOnAccountsUpdatedListener(this);
    super.onDestroy();
}

From source file:org.hfoss.posit.android.sync.Communicator.java

public static String getAuthKey(Context context) {
    AccountManager accountManager = AccountManager.get(context);

    // TODO: again just picking the first account here.. how are you
    // supposed to handle this?
    Account[] accounts = accountManager.getAccountsByType(SyncAdapter.ACCOUNT_TYPE);

    if (accounts.length == 0)
        return null;

    String authKey = null;/*from www .j a  v  a 2  s.c om*/
    try {
        authKey = accountManager.blockingGetAuthToken(accounts[0], SyncAdapter.AUTHTOKEN_TYPE,
                true /* notifyAuthFailure */);
    } catch (OperationCanceledException e) {
        Log.e(TAG, "getAuthKey(), cancelled during request: " + e.getMessage());
        e.printStackTrace();
    } catch (AuthenticatorException e) {
        Log.e(TAG, "getAuthKey(), authentication exception: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        Log.e(TAG, "getAuthKey() IOException" + e.getMessage());
        e.printStackTrace();
    } catch (IllegalStateException e) {
        Log.e(TAG, "getAuthKey() IllegalStateException" + e.getMessage());
        e.printStackTrace();
    }
    return authKey;
}

From source file:com.owncloud.android.authentication.AuthenticatorActivity.java

/**
 * {@inheritDoc}/* w w w .j  a  v  a  2s .c  o  m*/
 * 
 * IMPORTANT ENTRY POINT 1: activity is shown to the user
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.account_setup);
    mAuthMessage = (TextView) findViewById(R.id.auth_message);
    mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput);
    mHostUrlInput.setText(getString(R.string.server_url)); // valid although
                                                           // R.string.server_url
                                                           // is an empty
                                                           // string
    mUsernameInput = (EditText) findViewById(R.id.account_username);
    mPasswordInput = (EditText) findViewById(R.id.account_password);
    mPasswordInput2 = (EditText) findViewById(R.id.account_password2);
    mOAuthAuthEndpointText = (TextView) findViewById(R.id.oAuthEntryPoint_1);
    mOAuthTokenEndpointText = (TextView) findViewById(R.id.oAuthEntryPoint_2);
    mOAuth2Check = (CheckBox) findViewById(R.id.oauth_onOff_check);
    mOkButton = findViewById(R.id.buttonOK);
    mAuthStatusLayout = (TextView) findViewById(R.id.auth_status_text);

    // / set Host Url Input Enabled
    mHostUrlInputEnabled = getResources().getBoolean(R.bool.show_server_url_input);
    locationSpinner = (Spinner) findViewById(R.id.spinner1);

    // / complete label for 'register account' button
    Button b = (Button) findViewById(R.id.account_register);
    if (b != null) {
        b.setText(String.format(getString(R.string.auth_register), getString(R.string.app_name)));
    }

    // / initialization
    mAccountMgr = AccountManager.get(this);
    mNewCapturedUriFromOAuth2Redirection = null;
    mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE);
    mAccount = null;
    mHostBaseUrl = "";
    location = " ";//locationSpinner.getSelectedItem();
    locationSpinner.setOnItemSelectedListener(this);
    boolean refreshButtonEnabled = false;

    // URL input configuration applied
    if (!mHostUrlInputEnabled) {
        findViewById(R.id.hostUrlFrame).setVisibility(View.GONE);
        mRefreshButton = findViewById(R.id.centeredRefreshButton);

    } else {
        mRefreshButton = findViewById(R.id.embeddedRefreshButton);
    }

    if (savedInstanceState == null) {
        mResumed = false;
        // / connection state and info
        mAuthMessageVisibility = View.GONE;
        mServerStatusText = mServerStatusIcon = 0;
        mServerIsValid = false;
        mServerIsChecked = false;
        mIsSslConn = false;
        mAuthStatusText = mAuthStatusIcon = 0;

        // / retrieve extras from intent
        mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);

        if (mAccount != null) {
            String ocVersion = mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);
            Log.d("!!!!!!!!!!!!!!!!!!!!!!!!! ", mAccount.name);
            if (ocVersion != null) {
                mDiscoveredVersion = new OwnCloudVersion(ocVersion);
            }
            mHostBaseUrl = normalizeUrl(
                    mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL));
            mHostUrlInput.setText(mHostBaseUrl);

            String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
            Log.d("!!!!!!!!!!!!!!!!!!!!!!!!!4234 ", userName);
            mUsernameInput.setText(userName);
        }
        initAuthorizationMethod(); // checks intent and setup.xml to
                                   // determine mCurrentAuthorizationMethod
        mJustCreated = true;

        if (mAction == ACTION_UPDATE_TOKEN || !mHostUrlInputEnabled) {
            checkOcServer();
        }

    } else {
        mResumed = true;
        // / connection state and info
        mAuthMessageVisibility = savedInstanceState.getInt(KEY_AUTH_MESSAGE_VISIBILITY);
        mAuthMessageText = savedInstanceState.getString(KEY_AUTH_MESSAGE_TEXT);
        mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID);
        mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED);
        mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT);
        mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON);
        mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN);
        mAuthStatusText = savedInstanceState.getInt(KEY_AUTH_STATUS_TEXT);
        mAuthStatusIcon = savedInstanceState.getInt(KEY_AUTH_STATUS_ICON);
        if (savedInstanceState.getBoolean(KEY_PASSWORD_VISIBLE, false)) {
            showPassword();
        }

        // / server data
        String ocVersion = savedInstanceState.getString(KEY_OC_VERSION);
        if (ocVersion != null) {
            mDiscoveredVersion = new OwnCloudVersion(ocVersion);
        }
        mHostBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT);

        // account data, if updating
        mAccount = savedInstanceState.getParcelable(KEY_ACCOUNT);
        // Log.d("////////////////// ",mAccount.name);
        mAuthTokenType = savedInstanceState.getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);
        if (mAuthTokenType == null) {
            mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;

        }

        // check if server check was interrupted by a configuration change
        if (savedInstanceState.getBoolean(KEY_SERVER_CHECK_IN_PROGRESS, false)) {
            checkOcServer();
        }

        // refresh button enabled
        refreshButtonEnabled = savedInstanceState.getBoolean(KEY_REFRESH_BUTTON_ENABLED);

    }

    if (mAuthMessageVisibility == View.VISIBLE) {
        showAuthMessage(mAuthMessageText);
    } else {
        hideAuthMessage();
    }
    adaptViewAccordingToAuthenticationMethod();
    showServerStatus();
    showAuthStatus();

    if (mAction == ACTION_UPDATE_TOKEN) {
        // / lock things that should not change
        mHostUrlInput.setEnabled(false);
        mHostUrlInput.setFocusable(false);
        mUsernameInput.setEnabled(false);
        mUsernameInput.setFocusable(false);
        mOAuth2Check.setVisibility(View.GONE);
    }

    // if (mServerIsChecked && !mServerIsValid && mRefreshButtonEnabled)
    // showRefreshButton();
    if (mServerIsChecked && !mServerIsValid && refreshButtonEnabled)
        showRefreshButton();
    mOkButton.setEnabled(mServerIsValid); // state not automatically
                                          // recovered in configuration
                                          // changes

    if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)
            || !AUTH_OPTIONAL.equals(getString(R.string.auth_method_oauth2))) {
        mOAuth2Check.setVisibility(View.GONE);
    }

    mPasswordInput.setText(""); // clean password to avoid social hacking
                                // (disadvantage: password in removed if the
                                // device is turned aside)

    // / bind view elements to listeners and other friends
    mHostUrlInput.setOnFocusChangeListener(this);
    mHostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);
    mHostUrlInput.setOnEditorActionListener(this);
    mHostUrlInput.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            if (!mHostBaseUrl.equals(normalizeUrl(mHostUrlInput.getText().toString()))) {
                mOkButton.setEnabled(false);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!mResumed) {
                mAuthStatusIcon = 0;
                mAuthStatusText = 0;
                showAuthStatus();
            }
            mResumed = false;
        }
    });

    mPasswordInput.setOnFocusChangeListener(this);
    mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE);
    mPasswordInput.setOnEditorActionListener(this);
    mPasswordInput.setOnTouchListener(new RightDrawableOnTouchListener() {
        @Override
        public boolean onDrawableTouch(final MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                AuthenticatorActivity.this.onViewPasswordClick();
            }
            return true;
        }
    });

    findViewById(R.id.scroll).setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)
                        && mHostUrlInput.hasFocus()) {
                    checkOcServer();
                }
            }
            return false;
        }
    });
}

From source file:com.digitalarx.android.files.services.FileUploader.java

/**
 * Entry point to add one or several files to the queue of uploads.
 * //  w  w  w. j a v  a  2s.  c  o m
 * New uploads are added calling to startService(), resulting in a call to
 * this method. This ensures the service will keep on working although the
 * caller activity goes away.
 */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE)
            || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) {
        Log_OC.e(TAG, "Not enough information provided in intent");
        return Service.START_NOT_STICKY;
    }
    int uploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
    if (uploadType == -1) {
        Log_OC.e(TAG, "Incorrect upload type provided");
        return Service.START_NOT_STICKY;
    }
    Account account = intent.getParcelableExtra(KEY_ACCOUNT);

    String[] localPaths = null, remotePaths = null, mimeTypes = null;
    OCFile[] files = null;
    if (uploadType == UPLOAD_SINGLE_FILE) {

        if (intent.hasExtra(KEY_FILE)) {
            files = new OCFile[] { intent.getParcelableExtra(KEY_FILE) };

        } else {
            localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
            remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
            mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) };
        }

    } else { // mUploadType == UPLOAD_MULTIPLE_FILES

        if (intent.hasExtra(KEY_FILE)) {
            files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE); // TODO
                                                                         // will
                                                                         // this
                                                                         // casting
                                                                         // work
                                                                         // fine?

        } else {
            localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
            remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
            mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
        }
    }

    FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());

    boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
    boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false);
    int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_COPY);

    if (intent.hasExtra(KEY_FILE) && files == null) {
        Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent");
        return Service.START_NOT_STICKY;

    } else if (!intent.hasExtra(KEY_FILE)) {
        if (localPaths == null) {
            Log_OC.e(TAG, "Incorrect array for local paths provided in upload intent");
            return Service.START_NOT_STICKY;
        }
        if (remotePaths == null) {
            Log_OC.e(TAG, "Incorrect array for remote paths provided in upload intent");
            return Service.START_NOT_STICKY;
        }
        if (localPaths.length != remotePaths.length) {
            Log_OC.e(TAG, "Different number of remote paths and local paths!");
            return Service.START_NOT_STICKY;
        }

        files = new OCFile[localPaths.length];
        for (int i = 0; i < localPaths.length; i++) {
            files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i],
                    ((mimeTypes != null) ? mimeTypes[i] : (String) null), storageManager);
            if (files[i] == null) {
                // TODO @andomaex add failure Notification
                return Service.START_NOT_STICKY;
            }
        }
    }

    AccountManager aMgr = AccountManager.get(this);
    String version = aMgr.getUserData(account, Constants.KEY_OC_VERSION);
    OwnCloudVersion ocv = new OwnCloudVersion(version);

    boolean chunked = FileUploader.chunkedUploadIsSupported(ocv);
    AbstractList<String> requestedUploads = new Vector<String>();
    String uploadKey = null;
    UploadFileOperation newUpload = null;
    try {
        for (int i = 0; i < files.length; i++) {
            uploadKey = buildRemoteName(account, files[i].getRemotePath());
            newUpload = new UploadFileOperation(account, files[i], chunked, isInstant, forceOverwrite,
                    localAction, getApplicationContext());
            if (isInstant) {
                newUpload.setRemoteFolderToBeCreated();
            }
            mPendingUploads.putIfAbsent(uploadKey, newUpload); // Grants that the file only upload once time

            newUpload.addDatatransferProgressListener(this);
            newUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder);
            requestedUploads.add(uploadKey);
        }

    } catch (IllegalArgumentException e) {
        Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
        return START_NOT_STICKY;

    } catch (IllegalStateException e) {
        Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
        return START_NOT_STICKY;

    } catch (Exception e) {
        Log_OC.e(TAG, "Unexpected exception while processing upload intent", e);
        return START_NOT_STICKY;

    }

    if (requestedUploads.size() > 0) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = requestedUploads;
        mServiceHandler.sendMessage(msg);
    }
    Log_OC.i(TAG, "mPendingUploads size:" + mPendingUploads.size());
    return Service.START_NOT_STICKY;
}

From source file:com.owncloud.android.ui.activity.ManageAccountsActivity.java

/**
 * Callback executed after the {@link AccountManager} removed an account
 *
 * @param future    Result of the removal; future.getResult() is true if account was removed correctly.
 *///from   ww w . jav  a  2 s .c  o  m
@Override
public void run(AccountManagerFuture<Boolean> future) {
    if (future != null && future.isDone()) {
        Account account = new Account(mAccountBeingRemoved, MainApp.getAccountType());
        if (!AccountUtils.exists(account.name, MainApp.getAppContext())) {
            // Cancel transfers of the removed account
            if (mUploaderBinder != null) {
                mUploaderBinder.cancel(account);
            }
            if (mDownloaderBinder != null) {
                mDownloaderBinder.cancel(account);
            }
        }

        mAccountListAdapter = new AccountListAdapter(this, getAccountListItems(), mTintedCheck);
        mListView.setAdapter(mAccountListAdapter);

        AccountManager am = AccountManager.get(this);
        if (am.getAccountsByType(MainApp.getAccountType()).length == 0) {
            // Show create account screen if there isn't any account
            am.addAccount(MainApp.getAccountType(), null, null, null, this, null, null);
        } else { // at least one account left
            if (AccountUtils.getCurrentOwnCloudAccount(this) == null) {
                // current account was removed - set another as current
                String accountName = "";
                Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.getAccountType());
                if (accounts.length != 0) {
                    accountName = accounts[0].name;
                }
                AccountUtils.setCurrentOwnCloudAccount(this, accountName);
            }
        }
    }
}

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

/**
 * Get a preference from the Account./*from  w  w  w  .j av  a 2 s  .  c  o m*/
 *
 * Don't call this from the main thread - use an AsyncTask, for instance.
 *
 * @param context
 * @param prefKeyResId
 * @return
 */
@Nullable
private static String getStringPref(final Context context, final int prefKeyResId) {
    final AccountManager mgr = AccountManager.get(context);
    final Account account = getAccount(context);
    if (account == null) {
        return null;
    }

    //Note that this requires the AUTHENTICATE_ACCOUNTS permission on
    //SDK <=22.
    return mgr.getUserData(account, context.getString(prefKeyResId));
}

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

public void onLoadFinished(Loader<List<AccountInfo>> loader, List<AccountInfo> data) {
    int bigestAccountIndex = -1;
    int currCount = -1;

    if (sourceAccountAdapter != null) {
        List<AccountInfo> myAccountsData = new ArrayList<AccountInfo>();
        List<AccountInfo> newListData = new ArrayList<AccountInfo>();
        int listPos = 0;
        for (AccountInfo info : data) {
            if (Constants.ACCOUNT_TYPE.equals(info.accountType)) {
                myAccountsData.add(info);
                continue;
            }/*from ww  w .  j a  v  a  2s  . c  om*/
            if (info.getContactCount() > currCount) {
                currCount = info.getContactCount();
                bigestAccountIndex = listPos;
            }

            newListData.add(info);
            listPos++;
        }
        // If more than one of our accounts is here allow importing to
        // the other
        if (!myAccountsData.isEmpty()) {
            AccountManager accountManager = AccountManager.get(ImportActivity.this);
            Account[] myAccounts = accountManager.getAccountsByType(Constants.ACCOUNT_TYPE);
            if (myAccounts.length > 1) {
                for (AccountInfo accountInfo : myAccountsData) {
                    if (accountInfo.getContactCount() > currCount) {
                        currCount = accountInfo.getContactCount();
                        bigestAccountIndex = listPos;
                    }
                    newListData.add(accountInfo);
                    listPos++;
                }
            }
        }

        boolean containsOldData = sourceAccountAdapter.getCount() > 0;
        sourceAccountAdapter.setData(newListData);

        if (bigestAccountIndex >= 0 && !containsOldData) {
            Spinner spinner = (Spinner) findViewById(R.id.sourceAccountSpinner);
            if (spinner != null) {
                spinner.setSelection(bigestAccountIndex);
            }
        }
        updateBtnState();
    }
}