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.hemou.android.account.AccountUtils.java

/**
 * Get default account where password can be retrieved
 * //from   w w w .j av a2s  . c  o m
 * @param context
 * @return password accessible account or null if none
 */
public static Account getPasswordAccessibleAccount(final Context context) {
    AccountManager manager = AccountManager.get(context);
    Account[] accounts = manager.getAccountsByType(ACCOUNT_TYPE);
    if (accounts == null || accounts.length == 0)
        return null;

    try {
        accounts = getPasswordAccessibleAccounts(manager, accounts);
    } catch (AuthenticatorConflictException e) {
        return null;
    }
    return accounts != null && accounts.length > 0 ? accounts[0] : null;
}

From source file:info.semanticsoftware.semassist.android.activity.AuthenticationActivity.java

/** Sends an authentication request when the save button is pushed.
 * @param v view /*from  w ww .  j a  va2  s.  c  o  m*/
 */
public void onSaveClick(View v) {
    TextView tvUsername = (TextView) this.findViewById(R.id.uc_txt_username);
    TextView tvPassword = (TextView) this.findViewById(R.id.uc_txt_password);

    //Qualified username, i.e, user@semanticassistants.com
    String qUsername = tvUsername.getText().toString();
    String username = null;
    if (qUsername.indexOf("@") > 0) {
        username = qUsername.substring(0, qUsername.indexOf("@"));
    } else {
        username = qUsername;
    }
    String password = tvPassword.getText().toString();

    //TODO do client-side validation like password length etc.
    String response = authenicate(username, password);
    if (!response.equals(Constants.AUTHENTICATION_FAIL)) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        Editor editor = settings.edit();
        editor.putString("username", username);
        editor.putString("password", password);
        //FIXME replace this with a descent XML parser
        String acctype = "";
        int start = response.indexOf("<accType>");
        int end = response.indexOf("</accType>");
        if (start > -1 && end > -1) {
            acctype = response.substring(start + "<accType>".length(), end);
        }
        editor.putString("acctype", acctype);
        String sessionId = "";
        start = response.indexOf("<sessionId>");
        end = response.indexOf("</sessionId>");
        if (start > -1 && end > -1) {
            sessionId = response.substring(start + "<sessionId>".length(), end);
        }
        editor.putString("sessionId", sessionId);
        String reqNum = "";
        start = response.indexOf("<reqNum>");
        end = response.indexOf("</reqNum>");
        if (start > -1 && end > -1) {
            reqNum = response.substring(start + "<reqNum>".length(), end);
        }
        editor.putString("reqNum", reqNum);
        boolean result = editor.commit();
        if (result) {
            Toast.makeText(this, R.string.authenticationSuccess, Toast.LENGTH_LONG).show();
            String accountType = this.getIntent().getStringExtra("auth.token");
            if (accountType == null) {
                accountType = SemAssistAuthenticator.ACCOUNT_TYPE;
            }

            AccountManager accMgr = AccountManager.get(this);

            // Add the account to the Android Account Manager
            String accountName = username + "@semanticassistants.com";
            final Account account = new Account(accountName, accountType);
            accMgr.addAccountExplicitly(account, password, null);

            // Inform the caller (could be the Android Account Manager or the SA app) that the process was successful
            final Intent intent = new Intent();
            intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, accountName);
            intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);
            intent.putExtra(AccountManager.KEY_AUTHTOKEN, accountType);
            this.setAccountAuthenticatorResult(intent.getExtras());
            this.setResult(RESULT_OK, intent);
            this.finish();
        } else {
            Toast.makeText(this, "Could not write the preferences.", Toast.LENGTH_LONG).show();
        }
    } else {
        Toast.makeText(this, R.string.authenticationFail, Toast.LENGTH_LONG).show();
    }
}

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

public void messageDialogClosed(CharSequence dlgTitle, boolean positiveBtnPressed) {
    if (positiveBtnPressed) {
        // Delete all PaymentData
        AccountManager acm = AccountManager.get(this);
        Account[] accounts = acm.getAccountsByType(Constants.ACCOUNT_TYPE);
        for (Account account : accounts) {
            PaymentData paymentData = SyncUtils.getPayment(account, acm);
            if (paymentData != null) {
                SyncUtils.savePayment(account, acm, null, null);
                break;
            }//www.j  a  v  a2 s .  co  m
        }
    } else {
        finish();
    }
}

From source file:com.activiti.android.app.fragments.account.AccountEditFragment.java

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

    if (getArguments() != null) {
        accountId = getArguments().getLong(ARGUMENT_ACCOUNT_ID);
    }/*from   w  w  w  .j  av a 2  s.  c  om*/
    acc = ActivitiAccountManager.getInstance(getActivity()).getByAccountId(accountId);
    Uri serverUri = Uri.parse(acc.getServerUrl());

    if (serverUri.getPath().equals("/activiti-app")) {
        // It's default url
        https = ("https".equals(serverUri.getScheme().toLowerCase()));
        hostname = serverUri.getAuthority();
    } else {
        // It's not default we display full url in hostname
        hostname = acc.getServerUrl();
        hide(R.id.signing_https);
    }

    // TITLE
    TextView tv = (TextView) viewById(R.id.signin_title);
    tv.setText(R.string.settings_userinfo_account_summary);

    // USERNAME
    mEmailView = (MaterialAutoCompleteTextView) viewById(R.id.username);
    Account[] accounts = AccountManager.get(getActivity()).getAccounts();
    List<String> names = new ArrayList<>(accounts.length);
    String accountName;
    for (int i = 0; i < accounts.length; i++) {
        accountName = accounts[i].name;
        if (!TextUtils.isEmpty(accountName) && !names.contains(accountName)) {
            names.add(accounts[i].name);
        }
    }
    ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, names);
    mEmailView.setAdapter(adapter);
    mEmailView.setText(acc.getUsername());

    // PASSWORD
    mPasswordView = (EditText) viewById(R.id.password);
    mPasswordView.setText(acc.getPassword());

    Button mEmailSignInButton = (Button) viewById(R.id.email_sign_in_button);
    mEmailSignInButton.setText(R.string.general_action_confirm);
    mEmailSignInButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            attemptLogin();
        }
    });

    mProgressView = viewById(R.id.login_progress);
    mFormView = viewById(R.id.login_form);

    // Server part
    httpsView = (CheckBox) viewById(R.id.signing_https);
    httpsView.setChecked(https);
    hostnameView = (MaterialEditText) viewById(R.id.signing_hostname);
    hostnameView.setText(hostname);

    show(R.id.server_form);
}

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

/**
 * checks the set of actual accounts against the set of original accounts when the activity has been started.
 *
 * @return <code>true</code> if aacount list has changed, <code>false</code> if not
 *//*from  w w  w  .ja va 2s. c o  m*/
private boolean hasAccountListChanged() {
    Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.getAccountType());
    Set<String> actualAccounts = toAccountNameSet(accountList);
    return !mOriginalAccounts.equals(actualAccounts);
}

From source file:com.afwsamples.testdpc.provision.PostProvisioningTask.java

public Intent getPostProvisioningLaunchIntent(Intent intent) {
    // Enable the profile after provisioning is complete.
    Intent launch;//from   w  w  w. ja  va 2 s .  c o  m

    // Retreive the admin extras bundle, which we can use to determine the original context for
    // TestDPCs launch.
    PersistableBundle extras = intent.getParcelableExtra(EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE);
    String packageName = mContext.getPackageName();
    boolean synchronousAuthLaunch = LaunchIntentUtil.isSynchronousAuthLaunch(extras);
    boolean cosuLaunch = LaunchIntentUtil.isCosuLaunch(extras);
    boolean isProfileOwner = mDevicePolicyManager.isProfileOwnerApp(packageName);
    boolean isDeviceOwner = mDevicePolicyManager.isDeviceOwnerApp(packageName);

    // Drop out quickly if we're neither profile or device owner.
    if (!isProfileOwner && !isDeviceOwner) {
        return null;
    }

    if (isProfileOwner) {
        launch = new Intent(mContext, EnableProfileActivity.class);
    } else if (cosuLaunch) {
        launch = new Intent(mContext, EnableCosuActivity.class);
        launch.putExtra(EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE, extras);
    } else {
        launch = new Intent(mContext, EnableDeviceOwnerActivity.class);
    }

    if (synchronousAuthLaunch) {
        String accountName = LaunchIntentUtil.getAddedAccountName(extras);
        if (accountName != null) {
            launch.putExtra(LaunchIntentUtil.EXTRA_ACCOUNT_NAME, accountName);
        }
    }

    // For synchronous auth cases, we can assume accounts are already setup (or will be shortly,
    // as account migration for Profile Owner is asynchronous). For COSU we don't want to show
    // the account option to the user, as no accounts should be added for now.
    // In other cases, offer to add an account to the newly configured device/profile.
    if (!synchronousAuthLaunch && !cosuLaunch) {
        AccountManager accountManager = AccountManager.get(mContext);
        Account[] accounts = accountManager.getAccounts();
        if (accounts != null && accounts.length == 0) {
            // Add account after provisioning is complete.
            Intent addAccountIntent = new Intent(mContext, AddAccountActivity.class);
            addAccountIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            addAccountIntent.putExtra(AddAccountActivity.EXTRA_NEXT_ACTIVITY_INTENT, launch);
            return addAccountIntent;
        }
    }

    launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    return launch;
}

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

@Override
protected void onResume() {
    super.onResume();
    if (Sessions.isLogged(AccountManager.get(this))) {
        login();/* ww  w .  j  a  v a2  s  . co  m*/
    }
}

From source file:com.digitalarx.android.files.FileOperationsHelper.java

/**
 *  @return 'True' if the server supports the Share API
 *//*w w w  .  j av  a 2  s .  co  m*/
public boolean isSharedSupported() {
    if (mFileActivity.getAccount() != null) {
        AccountManager accountManager = AccountManager.get(mFileActivity);

        String version = accountManager.getUserData(mFileActivity.getAccount(), Constants.KEY_OC_VERSION);
        return (new OwnCloudVersion(version)).isSharedSupported();
    }
    return false;
}

From source file:com.netpace.expressit.fragment.MainGridFragment.java

private String getEmailId() {
    Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
    Account[] accounts = AccountManager.get(getActivity().getApplicationContext()).getAccounts();
    for (Account account : accounts) {
        if (emailPattern.matcher(account.name).matches()) {
            String possibleEmail = account.name;
            return possibleEmail;
        }/*from w w  w  .jav  a 2  s .  co  m*/
    }

    return null;
}

From source file:com.denizensoft.appcompatlib.AppActivity.java

@Override
public String appGetGoogleAccountString() {
    Pattern emailPattern = Patterns.EMAIL_ADDRESS;

    Account[] accounts = AccountManager.get(this).getAccounts();

    for (int i = 0; i < accounts.length; ++i) {
        Account a1 = accounts[i];// w  w  w . ja va  2s.  co m

        if (emailPattern.matcher(a1.name).matches()) {
            String possibleEmail = a1.name, stType = a1.type;

            Log.d("Superhero",
                    String.format("Found possible account %d: %s type: %s", i, possibleEmail, stType));

            if (stType.equals("com.google")) {
                return possibleEmail;
            }
        }
    }
    return null;
}