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:at.bitfire.davdroid.AccountSettings.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public AccountSettings(@NonNull Context context, @NonNull Account account) throws InvalidAccountException {
    this.context = context;
    this.account = account;

    accountManager = AccountManager.get(context);

    synchronized (AccountSettings.class) {
        String versionStr = accountManager.getUserData(account, KEY_SETTINGS_VERSION);
        if (versionStr == null)
            throw new InvalidAccountException(account);

        int version = 0;
        try {//from   www  .jav a  2s.c om
            version = Integer.parseInt(versionStr);
        } catch (NumberFormatException ignored) {
        }
        App.log.info("Account " + account.name + " has version " + version + ", current version: "
                + CURRENT_VERSION);

        if (version < CURRENT_VERSION) {
            Notification notify = new NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.ic_new_releases_light).setLargeIcon(App.getLauncherBitmap(context))
                    .setContentTitle(context.getString(R.string.settings_version_update))
                    .setContentText(context.getString(R.string.settings_version_update_settings_updated))
                    .setSubText(context.getString(R.string.settings_version_update_install_hint))
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(context.getString(R.string.settings_version_update_settings_updated)))
                    .setCategory(NotificationCompat.CATEGORY_SYSTEM)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setContentIntent(PendingIntent.getActivity(context, 0,
                            new Intent(Intent.ACTION_VIEW, Constants.webUri.buildUpon()
                                    .appendEncodedPath("faq/entry/davdroid-not-working-after-update/").build()),
                            PendingIntent.FLAG_CANCEL_CURRENT))
                    .setLocalOnly(true).build();
            NotificationManagerCompat nm = NotificationManagerCompat.from(context);
            nm.notify(Constants.NOTIFICATION_ACCOUNT_SETTINGS_UPDATED, notify);

            update(version);
        }
    }
}

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

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

    mTintedCheck = ContextCompat.getDrawable(this, R.drawable.ic_current_white);
    mTintedCheck = DrawableCompat.wrap(mTintedCheck);
    int tint = ContextCompat.getColor(this, R.color.actionbar_start_color);
    DrawableCompat.setTint(mTintedCheck, tint);

    setContentView(R.layout.accounts_layout);

    mListView = findViewById(R.id.account_list);
    mListView.setFilterTouchesWhenObscured(true);

    setupToolbar();/*from  w w  w.  ja  va2s .  c  o m*/
    updateActionBarTitleAndHomeButtonByString(getResources().getString(R.string.prefs_manage_accounts));

    Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.getAccountType());
    mOriginalAccounts = toAccountNameSet(accountList);
    mOriginalCurrentAccount = AccountUtils.getCurrentOwnCloudAccount(this).name;

    setAccount(AccountUtils.getCurrentOwnCloudAccount(this));
    onAccountSet(false);

    initializeComponentGetters();

    // added click listener to switch account
    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switchAccount(position);
        }
    });
}

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

/**
 * {@inheritDoc}/* ww  w. ja  v  a  2s .  c o  m*/
 */
@Override
public void onCreate(Bundle icicle) {
    Log.i(tag, "onCreate(" + icicle + ")");
    super.onCreate(icicle);
    mAccountManager = AccountManager.get(this);
    Log.i(tag, "loading data from Intent");
    final Intent intent = getIntent();
    mUsername = intent.getStringExtra(PARAM_USERNAME);
    mAuthtokenType = intent.getStringExtra(PARAM_AUTHTOKEN_TYPE);
    mRequestNewAccount = mUsername == null;
    mConfirmCredentials = intent.getBooleanExtra(PARAM_CONFIRMCREDENTIALS, false);

    Log.i(tag, "request new: " + mRequestNewAccount + " ,ConfirmCredentials: " + mConfirmCredentials);
    requestWindowFeature(Window.FEATURE_LEFT_ICON);
    setContentView(R.layout.login_activity);
    getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_alert);

    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.country_code_array,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);
    setSpinnerCountry(spinner);
    mMessage = (TextView) findViewById(R.id.message);
    mUsernameEdit = (EditText) findViewById(R.id.username_edit);
    mPasswordEdit = (EditText) findViewById(R.id.password_edit);
    mPhoneEdit = (EditText) findViewById(R.id.phone_edit);
    getPhoneNumber(getApplicationContext());
    mUsernameEdit.setText(mUsername);
    mMessage.setText(getMessage());
}

From source file:com.arthackday.killerapp.util.Util.java

public String getGoogleAuth(String type) {
    AccountManager mgr = AccountManager.get(activity);
    Account[] accts = mgr.getAccountsByType("com.google");

    if (accts.length == 0) {
        return null;
    }/*w ww  .  j  ava  2  s .  c o m*/

    try {
        Account acct = accts[0];
        Log.d(LOG_TAG, "acct name=" + acct.name);
        AccountManagerFuture<Bundle> accountManagerFuture = mgr.getAuthToken(acct, type, null, activity, null,
                null);

        Bundle authTokenBundle = accountManagerFuture.getResult();

        if (authTokenBundle.containsKey(AccountManager.KEY_INTENT)) {
            Intent authRequestIntent = (Intent) authTokenBundle.get(AccountManager.KEY_INTENT);
            activity.startActivity(authRequestIntent);
        }

        return authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();
    } catch (OperationCanceledException e) {
        e.printStackTrace();
    } catch (AuthenticatorException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.clearcenter.mobile_demo.mdAuthenticatorActivity.java

public void onCreate(Bundle bundle) {
    Log.i(TAG, "onCreate(" + bundle + ")");
    super.onCreate(bundle);
    setContentView(R.layout.login_activity);

    account_manager = AccountManager.get(this);

    Log.i(TAG, "loading data from Intent");
    final Intent intent = getIntent();

    nickname = intent.getStringExtra(PARAM_NICKNAME);
    username = intent.getStringExtra(PARAM_USERNAME);
    hostname = intent.getStringExtra(PARAM_HOSTNAME);

    request_new_account = nickname == null;
    confirm_credentials = intent.getBooleanExtra(PARAM_CONFIRM_CREDENTIALS, false);
    Log.i(TAG, "new account? " + request_new_account + ", confirm credentials? " + confirm_credentials);

    scroll_view = (ScrollView) findViewById(R.id.scroll_view);

    message = (TextView) findViewById(R.id.message);

    nickname_label = (TextView) findViewById(R.id.nickname_label);
    nickname_edit = (EditText) findViewById(R.id.nickname_edit);
    nickname_label.setVisibility(request_new_account ? View.VISIBLE : View.GONE);
    nickname_edit.setVisibility(request_new_account ? View.VISIBLE : View.GONE);
    if (nickname != null)
        nickname_edit.setText(nickname);

    hostname_label = (TextView) findViewById(R.id.hostname_label);
    hostname_edit = (EditText) findViewById(R.id.hostname_edit);
    hostname_label.setVisibility(request_new_account ? View.VISIBLE : View.GONE);
    hostname_edit.setVisibility(request_new_account ? View.VISIBLE : View.GONE);
    if (hostname != null)
        hostname_edit.setText(hostname);

    username_label = (TextView) findViewById(R.id.username_label);
    username_edit = (EditText) findViewById(R.id.username_edit);
    username_label.setVisibility(request_new_account ? View.VISIBLE : View.GONE);
    username_edit.setVisibility(request_new_account ? View.VISIBLE : View.GONE);
    if (username != null)
        username_edit.setText(username);

    password_edit = (EditText) findViewById(R.id.password_edit);

    if (confirm_credentials) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager notification_manager;
        notification_manager = (NotificationManager) getApplicationContext().getSystemService(ns);
        notification_manager.cancelAll();
        Log.i(TAG, "TODO: Cancel all notifications?");
    }/*from   w w w  .  ja va 2  s.  com*/

    if (!TextUtils.isEmpty(nickname))
        nickname_edit.setText(nickname);

    if (request_new_account)
        message.setText(getText(R.string.login_activity_new_account));
    else if (confirm_credentials) {
        message.setText(getText(R.string.login_activity_confirm_credentials));
    }

    try {
        mdSSLUtil.DisableSecurity();
    } catch (GeneralSecurityException e) {
        Toast.makeText(getApplicationContext(), e.getMessage(), 4).show();
    }
}

From source file:com.hyrt.cnp.account.AccountAuthenticator.java

@Override
public Bundle getAuthToken(final AccountAuthenticatorResponse response, final Account account,
        final String authTokenType, final Bundle options) throws NetworkErrorException {
    Log.d(TAG, "Retrieving OAuth2 token");

    final Bundle bundle = new Bundle();

    if (!ACCOUNT_TYPE.equals(authTokenType))
        return bundle;

    AccountManager am = AccountManager.get(context);
    String password = am.getPassword(account);
    if (TextUtils.isEmpty(password)) {
        bundle.putParcelable(KEY_INTENT, createLoginIntent(response));
        return bundle;
    }//  w  w  w  . ja  v a 2 s  . com
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.set("username", account.name);
    params.set("password", password);
    User.UserModel userModel = null;
    try {
        userModel = getCustomRestTemplate().postForObject("http://api.chinaxueqian.com/account/login", params,
                User.UserModel.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (userModel == null || userModel.getData() == null || TextUtils.isEmpty(userModel.getData().getToken()))
        bundle.putParcelable(KEY_INTENT, createLoginIntent(response));
    else {
        bundle.putString(KEY_ACCOUNT_NAME, account.name);
        bundle.putString(KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
        bundle.putString(KEY_AUTHTOKEN, userModel.getData().getToken() + "&uuid="
                + userModel.getData().getUuid() + "&sid=" + userModel.getData().getNursery_id());
        am.clearPassword(account);
    }
    return bundle;
}

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

/**
 * This returns null if there is no account (not even an anonymous account).
 * Don't call this from the main thread - use an AsyncTask, for instance.
 *
 * @param context/*from  www.j  av a2  s. co  m*/
 * @return
 */
@Nullable
public static LoginDetails getAccountLoginDetails(final Context context) {
    final AccountManager mgr = AccountManager.get(context);
    if (mgr == null) {
        Log.error(
                "getAccountLoginDetails(): getAccountLoginDetails() failed because AccountManager.get() returned null.");
        return null;
    }

    final Account account = getAccount(mgr);
    if (account == null) {
        Log.error(
                "getAccountLoginDetails(): getAccountLoginDetails() failed because getAccount() returned null. ");
        return null;
    }

    //Make sure that this has not been unset somehow:
    setAutomaticAccountSync(context, account);

    final LoginDetails result = new LoginDetails();

    //Avoid showing our anonymous account name in the UI.
    //Also, an anonymous account never has an auth_api_key.
    result.isAnonymous = TextUtils.equals(account.name, ACCOUNT_NAME_ANONYMOUS);
    if (result.isAnonymous) {
        return result; //Return a mostly-empty empty (but not null) LoginDetails.
    }

    result.name = account.name;

    //Note that this requires the USE_CREDENTIALS permission on
    //SDK <=22.
    final AccountManagerFuture<Bundle> response = mgr.getAuthToken(account, ACCOUNT_AUTHTOKEN_TYPE, null, null,
            null, null);
    try {
        final Bundle bundle = response.getResult();
        if (bundle == null) {
            //TODO: Let the caller catch this?
            Log.error(
                    "getAccountLoginDetails(): getAccountLoginDetails() failed because getAuthToken() returned a null response result bundle.");
            return null;
        }

        result.authApiKey = bundle.getString(AccountManager.KEY_AUTHTOKEN);
        return result;
    } catch (final OperationCanceledException e) {
        //TODO: Let the caller catch this?
        Log.error("getAccountLoginDetails(): getAccountLoginDetails() failed", e);
        return null;
    } catch (final AuthenticatorException e) {
        //TODO: Let the caller catch this?
        Log.error("getAccountLoginDetails(): getAccountLoginDetails() failed", e);
        return null;
    } catch (final IOException e) {
        //TODO: Let the caller catch this?
        Log.error("getAccountLoginDetails(): getAccountLoginDetails() failed", e);
        return null;
    }
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    api = new TimeTableAPI(TimeTableActivity.this);

    setContentView(R.layout.timetable_main);

    fragmentPageAdapter = new MyAdapter(getSupportFragmentManager());
    accountManager = AccountManager.get(getApplicationContext());
    preferences = getPreferences(MODE_PRIVATE);

    dayPager = (ViewPager) findViewById(R.id.day_pager);
    dayPager.setAdapter(fragmentPageAdapter);

    final float density = getResources().getDisplayMetrics().density;

    TitlePageIndicator titleIndicator = (TitlePageIndicator) findViewById(R.id.titles);
    titleIndicator.setViewPager(dayPager);

    titleIndicator.setBackgroundColor(getResources().getColor(android.R.color.background_dark)); // 0x330065A3
    titleIndicator.setFooterColor(0xFF0065A3);
    titleIndicator.setFooterLineHeight(4 * density); // 1dp
    titleIndicator.setFooterIndicatorHeight(6 * density); // 3dp
    titleIndicator.setFooterIndicatorStyle(IndicatorStyle.Triangle);
    titleIndicator.setTextColor(getResources().getColor(android.R.color.primary_text_dark));
    titleIndicator.setTextColor(getResources().getColor(android.R.color.secondary_text_dark));

    datebox = (TextView) findViewById(R.id.date_value);
    weekbox = (TextView) findViewById(R.id.week_value);

    Date date = new Date();
    weekbox.setText(DateHelper.formatToWeekNumber(date));

    UiWeek lastInstance = (UiWeek) getLastCustomNonConfigurationInstance();
    if (lastInstance != null) {
        Log.i(LOGGING_TAG, "Creating Activity from lastInstance.");
        // there was a screen orientation change.
        // we can don't have to create the ui...
        week = lastInstance;//from   w  ww.  j  av  a 2s  .  co  m
        datebox.setText(DateHelper.formatToUserFriendlyFormat(week.getLastUpdate()));
    } else if (savedInstanceState != null && savedInstanceState.containsKey(SAVED_INSTANCE_TIMETABLE_WEEK)) {
        Log.i(LOGGING_TAG, "Creating Activity from savedInstanceState.");
        // the state of the app was saved, so we can just update the ui
        week = (UiWeek) savedInstanceState.get(SAVED_INSTANCE_TIMETABLE_WEEK);
        datebox.setText(DateHelper.formatToUserFriendlyFormat(week.getLastUpdate()));
    } else {
        Log.i(LOGGING_TAG, "Creating Activity from scratch.");
        // no data available, read it!
        reloadCurrentTab();
        startRequest(date, false);
    }

}

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

private void getIdentity() {
    if (mAccountName == null || mAccountName.isEmpty()) {
        replyWithError("Empty account name.");
        return;//from  w  w w .j  av a  2s . co  m
    }
    Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");
    Account account = null;
    for (int i = 0; i < accounts.length; i++) {
        if (accounts[i].name.equals(mAccountName)) {
            account = accounts[i];
        }
    }
    if (account == null) {
        replyWithError("Couldn't find Google account with name: " + mAccountName);
        return;
    }
    AccountManager.get(this).getAuthToken(account, OAUTH_SCOPE, new Bundle(), false, new OnTokenAcquired(),
            new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    replyWithError("Error getting auth token: " + msg.toString());
                    return true;
                }
            }));
}