Example usage for android.accounts AccountManager getPassword

List of usage examples for android.accounts AccountManager getPassword

Introduction

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

Prototype

public String getPassword(final Account account) 

Source Link

Document

Gets the saved password associated with the account.

Usage

From source file:com.nextgis.maplibui.SelectNGWResourceDialog.java

protected Connections fillConnections() {
    Connections connections = new Connections(getString(R.string.accounts));
    final AccountManager accountManager = AccountManager.get(getActivity());
    for (Account account : accountManager.getAccountsByType(NGW_ACCOUNT_TYPE)) {
        String url = accountManager.getUserData(account, "url");
        String password = accountManager.getPassword(account);
        String login = accountManager.getUserData(account, "login");
        connections.add(new Connection(account.name, login, password, url));
    }//w  ww.  j  ava  2s . c  o m
    return connections;
}

From source file:pt.up.mobile.authenticator.Authenticator.java

@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType,
        Bundle loginOptions) throws NetworkErrorException {
    Log.v(TAG, "getAuthToken()");

    // If the caller requested an authToken type we don't support, then
    // return an error
    if (!authTokenType.equals(Constants.AUTHTOKEN_TYPE)) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType");
        return result;
    }//from  ww w . j  a  v  a2s. c o  m
    try {
        final AccountManager am = AccountManager.get(mContext);
        final String peek = am.peekAuthToken(account, authTokenType);
        if (peek != null) {
            final Bundle result = new Bundle();
            result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
            result.putString(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
            result.putString(AccountManager.KEY_AUTHTOKEN, peek);
            return result;
        }
        // Extract the username and password from the Account Manager, and
        // ask
        // the server for an appropriate AuthToken.
        final String password = am.getPassword(account);
        if (password != null) {
            String[] reply;

            reply = SifeupAPI.authenticate(account.name, password, mContext);
            final String authToken = reply[1];
            if (!TextUtils.isEmpty(authToken)) {
                final Bundle result = new Bundle();
                result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
                result.putString(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
                result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
                return result;
            }
        }

    } catch (AuthenticationException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
        throw new NetworkErrorException();
    }
    // If we get here, then we couldn't access the user's password - so we
    // need to re-prompt them for their credentials. We do that by creating
    // an intent to display our AuthenticatorActivity panel.
    final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
    intent.putExtra(AuthenticatorActivity.PARAM_CONFIRM_CREDENTIALS, true);
    intent.putExtra(AuthenticatorActivity.PARAM_USERNAME, account.name);
    intent.putExtra(AuthenticatorActivity.PARAM_AUTHTOKEN_TYPE, authTokenType);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
    final Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    return bundle;
}

From source file:de.kollode.redminebrowser.sync.SyncHelper.java

void performSync(SyncResult syncResult, Account account) throws IOException {

    NotificationManager mNotificationManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);

    android.support.v4.app.NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
    mBuilder.setContentTitle("Projects").setContentText("Syncing in progress")
            .setSmallIcon(R.drawable.ic_launcher);

    final ContentResolver resolver = mContext.getContentResolver();
    ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);

    AccountManager accMgr = AccountManager.get(this.mContext);
    String serverUrl = accMgr.getUserData(account, "serverUrl");

    if (isOnline()) {

        final long startRemote = System.currentTimeMillis();

        int syncedProjects = 0;
        Log.i(sTag, "Remote syncing speakers");
        Log.i(sTag, serverUrl);/*  ww  w .ja v  a 2 s.c o m*/

        try {

            int offset = 0;
            int numberOfProjects;
            int limit = 100;
            boolean loadMore = true;

            do {
                String restQuery = "sort=updated_on:desc&limit=" + limit + "&offset=" + offset + "&key="
                        + accMgr.getPassword(account);

                Log.d(sTag, "REST URL: " + serverUrl + "/projects.json?" + restQuery);
                JSONObject projectsJson = getJsonFromUrl(serverUrl + "/projects.json?" + restQuery);

                numberOfProjects = projectsJson.getInt("total_count");
                mBuilder.setProgress(numberOfProjects, syncedProjects, false);
                mNotificationManager.notify(0, mBuilder.build());

                if (numberOfProjects < limit + offset) {
                    Log.d(sTag, "Enough Projects");
                    loadMore = false;
                } else {
                    Log.d(sTag, "More Projects");
                    offset += limit;
                }

                JSONArray projects = projectsJson.getJSONArray("projects");

                for (int i = 0; i < projects.length(); i++) {

                    JSONObject project = projects.getJSONObject(i);
                    Builder projectBuilder = ContentProviderOperation
                            .newInsert(Project.buildProjectsUri(account.name));

                    Log.d(sTag, project.toString());

                    try {
                        projectBuilder.withValue(Project.PARENT, project.getJSONObject("parent").getInt("id"));
                    } catch (Exception e) {

                    }

                    batch.add(projectBuilder.withValue(BaseColumns._ID, project.getInt("id"))
                            .withValue(Project.NAME, project.getString("name"))
                            .withValue(Project.IDENTIFIER, project.getString("identifier"))
                            .withValue(Project.UPDATED, System.currentTimeMillis())
                            .withValue(Project.CREATED, System.currentTimeMillis())
                            .withValue(Project.CREATED_ON, project.getString("created_on"))
                            .withValue(Project.UPDATED_ON, project.getString("updated_on")).build());

                    mBuilder.setProgress(numberOfProjects, syncedProjects++, false);
                    mNotificationManager.notify(0, mBuilder.build());
                }
            } while (loadMore && !this.isCanceled());

            try {
                // Apply all queued up batch operations for local data.
                resolver.applyBatch(RedmineTables.CONTENT_AUTHORITY, batch);
            } catch (RemoteException e) {
                throw new RuntimeException("Problem applying batch operation", e);
            } catch (OperationApplicationException e) {
                throw new RuntimeException("Problem applying batch operation", e);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (this.isCanceled()) {
            mBuilder.setContentText("Sync was canceled").setProgress(0, 0, false);
        } else {
            mBuilder.setContentText("Sync complete").setProgress(0, 0, false);
        }
        mNotificationManager.notify(0, mBuilder.build());

        syncResult.delayUntil = ((long) 60 * 60);

        Log.d(sTag, "Remote sync took " + (System.currentTimeMillis() - startRemote) + "ms");
        Log.d(sTag, "Number of projects: " + syncedProjects);
    }
}

From source file:com.nextgis.maplibui.SelectNGWResourceDialog.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == ADDACCOUNT_CODE) {
        if (resultCode != Activity.RESULT_CANCELED) {
            //search new account and add it
            final AccountManager accountManager = AccountManager.get(getActivity());
            Connections connections = mListAdapter.getConnections();
            for (Account account : accountManager.getAccountsByType(NGW_ACCOUNT_TYPE)) {
                boolean find = false;
                for (int i = 0; i < connections.getChildrenCount(); i++) {
                    Connection connection = (Connection) connections.getChild(i);
                    if (null != connection && connection.getName().equals(account.name)) {
                        find = true;//from w  w  w . ja  va 2  s.  c o  m
                        break;
                    }
                }

                if (!find) {
                    String url = accountManager.getUserData(account, "url");
                    String password = accountManager.getPassword(account);
                    String login = accountManager.getUserData(account, "login");
                    connections.add(new Connection(account.name, login, password, url));
                    mListAdapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    } else
        super.onActivityResult(requestCode, resultCode, data);
}

From source file:mobile.tiis.appv2.LoginActivity.java

/**
 * This method will get called when the user presses the login
 * button.//from  ww  w  .  ja  va2s . c  om
 *
 * <p>This method will check with checkRequiredFields to make
 * sure if it will process the click.
 */

public void onClick(View v) {
    Log.d(TAG, "clicked login");
    //get inserted username and password
    username = usernameEditText.getText().toString().trim();
    password = passwordEditText.getText().toString().trim();

    //check if required fields are not empty
    if (checkRequiredFields()) {
        Log.d(TAG, "check passed");
        progressDialog.setMessage("Signing in. \nPlease wait ...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();

        loginButton.setEnabled(false);
        //continue with device online
        if (Utils.isOnline(LoginActivity.this)) {

            boolean loggedIn = false;
            if (databaseHandler.getAllUsers().size() != 0) {
                //Checking if the user had once logged in
                //check if user is already registered with AccountManager
                AccountManager accountManager = AccountManager.get(LoginActivity.this);
                Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE);

                //go through all accounts found in Account Manager
                for (Account account : accounts) {
                    //if there is a match set login as true and go to Home Activity
                    if (account.name.equalsIgnoreCase(username)
                            && accountManager.getPassword(account).equals(password)) {
                        //Activity mobile.tiis.app.LoginActivity has leaked window error was showing
                        //this piece of code handles it, nonetheless in prod time the error  would not show
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        SharedPreferences.Editor editor = PreferenceManager
                                .getDefaultSharedPreferences(getApplicationContext()).edit();
                        editor.putBoolean("secondSyncNeeded", true);
                        editor.commit();

                        Intent intent = new Intent(LoginActivity.this, LotSettingsActivity.class);

                        Log.d(TAG, "initiating offline for " + username + " password = " + password);
                        app.initializeOffline(username, password);

                        Log.d(TAG, "initiating offline for " + username + " password = " + password);

                        app.setUsername(username);
                        Log.d("supportLog", "call the loggin first time before the account was found");
                        startActivity(intent);
                        loggedIn = true;
                    }
                }
            } else {
                SharedPreferences preferenceManager = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext());
                preferenceManager.edit().putBoolean("synchronization_needed", true);
            }
            if (!loggedIn) {

                //build webservice url
                StringBuilder webServiceLoginURL = createWebServiceLoginURL(username, password, regId);

                //call web service to pull user info and send to account manager
                try {
                    startWebService(webServiceLoginURL, username, password);
                } catch (NullPointerException e) {
                    startWebService(webServiceLoginURL, username, password);
                }
            }

        } else {

            //check if user is already registered with AccountManager
            AccountManager accountManager = AccountManager.get(LoginActivity.this);
            Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE);
            boolean loggedIn = false;
            if (databaseHandler.getAllUsers().size() != 0) {

                //go through all accounts found in AM
                for (Account account : accounts) {
                    //if there is a match set login as true and go to Home Activity
                    if (account.name.equalsIgnoreCase(username)
                            && accountManager.getPassword(account).equals(password)) {
                        //Activity mobile.tiis.app.LoginActivity has leaked window error was showing
                        //this piece of code handles it, nonetheless in prod time the error  would not show
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        SharedPreferences.Editor editor = PreferenceManager
                                .getDefaultSharedPreferences(getApplicationContext()).edit();
                        editor.putBoolean("secondSyncNeeded", true);
                        editor.commit();

                        Intent intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                        app.setUsername(username);
                        Log.d(TAG, "initiating offline for " + username + " password = " + password);
                        app.initializeOffline(username, password);
                        startActivity(intent);
                        loggedIn = true;
                    }
                }
            } else {
                SharedPreferences preferenceManager = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext());
                preferenceManager.edit().putBoolean("synchronization_needed", true);
            }
            //if login failed, show error
            if (!loggedIn) {
                progressDialog.dismiss();
                toastMessage("Login failed.\nPlease check your details or be online for first login!");
                loginButton.setEnabled(true);
            }
        }
    }
}

From source file:edu.mit.mobile.android.locast.net.NetworkClient.java

public void setCredentialsFromAccount(Account account) {
    final AccountManager am = AccountManager.get(mContext);

    if (Authenticator.DEMO_ACCOUNT.equals(account.name)) {
        if (DEBUG) {
            Log.i(TAG, "demo account is being used");
        }//  w w  w.  ja  va2 s  . c  o  m
        return;
    }

    setCredentials(account.name, am.getPassword(account));
}

From source file:org.tigase.messenger.phone.pro.service.XMPPService.java

private final void updateJaxmppInstances() {
    final HashSet<BareJID> accountsJids = new HashSet<BareJID>();
    for (JaxmppCore jaxmpp : multiJaxmpp.get()) {
        accountsJids.add(jaxmpp.getSessionObject().getUserBareJid());
    }/*w  w  w .ja  va  2s  .  c o  m*/

    final AccountManager am = AccountManager.get(this);
    for (Account account : am.getAccountsByType(Authenticator.ACCOUNT_TYPE)) {
        BareJID accountJid = BareJID.bareJIDInstance(account.name);
        Jaxmpp jaxmpp = multiJaxmpp.get(accountJid);
        if (jaxmpp == null) {
            jaxmpp = createJaxmpp(accountJid, account.hashCode());
            multiJaxmpp.add(jaxmpp);
        }

        // workaround for unknown certificate error
        jaxmpp.getSessionObject().setProperty("jaxmpp#ThrowedException", null);

        String password = am.getPassword(account);
        String nickname = am.getUserData(account, AccountsConstants.FIELD_NICKNAME);
        String hostname = am.getUserData(account, AccountsConstants.FIELD_HOSTNAME);
        String resource = am.getUserData(account, AccountsConstants.FIELD_RESOURCE);
        hostname = hostname == null ? null : hostname.trim();

        jaxmpp.getSessionObject().setUserProperty(SessionObject.PASSWORD, password);
        jaxmpp.getSessionObject().setUserProperty(SessionObject.NICKNAME, nickname);
        if (hostname != null && TextUtils.isEmpty(hostname))
            hostname = null;
        // sessionObject.setUserProperty(SessionObject.DOMAIN_NAME,
        // hostname);
        if (TextUtils.isEmpty(resource))
            resource = null;
        jaxmpp.getSessionObject().setUserProperty(SessionObject.RESOURCE, resource);

        MobileModeFeature.updateSettings(account, jaxmpp, this);

        boolean disabled = !Boolean.parseBoolean(am.getUserData(account, AccountsConstants.FIELD_ACTIVE));
        jaxmpp.getSessionObject().setUserProperty("CC:DISABLED", disabled);

        if (disabled) {
            if (jaxmpp.isConnected()) {
                this.disconnectJaxmpp(jaxmpp, true);
            }
        } else {
            if (!jaxmpp.isConnected()) {
                this.connectJaxmpp(jaxmpp, 1L);
            }
        }

        accountsJids.remove(accountJid);
    }

    for (BareJID accountJid : accountsJids) {
        final Jaxmpp jaxmpp = multiJaxmpp.get(accountJid);
        if (jaxmpp != null) {
            multiJaxmpp.remove(jaxmpp);
            (new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    try {
                        jaxmpp.disconnect();
                        // clear presences for account?
                        // app.clearPresences(jaxmpp.getSessionObject(),
                        // false);
                        // is this needed any more??
                        // JaxmppService.this.rosterProvider.resetStatus(jaxmpp.getSessionObject());
                    } catch (Exception ex) {
                        Log.e(TAG, "Can't disconnect", ex);
                    }

                    return null;
                }
            }).execute();
        }
    }

    dataRemover.removeUnusedData(this);
}