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

/**
 * {@inheritDoc}//  w w w. jav  a  2  s  . c om
 */
@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(EXTRA_USERNAME);
    mAuthtokenType = intent.getStringExtra(EXTRA_AUTHTOKEN_TYPE);
    mRequestNewAccount = mUsername == null;
    mConfirmCredentials = intent.getBooleanExtra(EXTRA_CONFIRMCREDENTIALS, false);

    Log.i(TAG, "    request new: " + mRequestNewAccount);
    requestWindowFeature(Window.FEATURE_LEFT_ICON);
    // make the title based on the app name.
    setTitle(getString(R.string.login_title, getString(R.string.app_name)));

    setContentView(R.layout.login);
    // this is done this way, so the associated icon is managed in XML.
    try {
        getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON,
                getPackageManager().getActivityIcon(getComponentName()));
    } catch (final NameNotFoundException e) {
        e.printStackTrace();
    }

    mMessage = (TextView) findViewById(R.id.message);
    mUsernameEdit = (EditText) findViewById(R.id.username);
    mPasswordEdit = (EditText) findViewById(R.id.password);
    mPasswordEdit.setOnEditorActionListener(this);
    findViewById(R.id.login).setOnClickListener(this);
    findViewById(R.id.cancel).setOnClickListener(this);
    ((Button) findViewById(R.id.register)).setOnClickListener(this);

    mUsernameEdit.setText(mUsername);

    mAuthenticationTask = (AuthenticationTask) getLastNonConfigurationInstance();
    if (mAuthenticationTask != null) {
        mAuthenticationTask.attach(this);
    }
}

From source file:com.manning.androidhacks.hack023.authenticator.Authenticator.java

@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType,
        Bundle options) throws NetworkErrorException {

    if (!authTokenType.equals(AuthenticatorActivity.PARAM_AUTHTOKEN_TYPE)) {

        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType");

        return result;
    }//  ww w .ja va  2 s .  c o  m

    final AccountManager am = AccountManager.get(mContext);
    final String password = am.getPassword(account);

    if (password != null) {
        boolean verified = false;

        String loginResponse = null;
        try {
            loginResponse = LoginServiceImpl.sendCredentials(account.name, password);
            verified = LoginServiceImpl.hasLoggedIn(loginResponse);
        } catch (AndroidHacksException e) {
            verified = false;
        }

        if (verified) {
            final Bundle result = new Bundle();
            result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
            result.putString(AccountManager.KEY_ACCOUNT_TYPE, AuthenticatorActivity.PARAM_ACCOUNT_TYPE);

            return result;
        }
    }
    // Password is missing or incorrect
    final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
    intent.putExtra(AuthenticatorActivity.PARAM_USER, 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:com.gigathinking.simpleapplock.RegisterDevice.java

private boolean registerDevice() {
    String username;/*  ww  w  . j  a v a 2  s .  c o m*/
    String device = Build.MODEL;
    String version = Build.VERSION.RELEASE;
    if (prefs.getString(mContext.getString(R.string.user_name), null) == null) {
        AccountManager manager = AccountManager.get(mContext);
        Account[] accounts = manager != null ? manager.getAccountsByType("com.google") : new Account[0];
        if (accounts.length == 0) {
            return false;
        }
        username = accounts[0].name.split("@")[0];
        prefs.edit().putString(mContext.getString(R.string.user_name), username).commit();
    } else {
        username = prefs.getString(mContext.getString(R.string.user_name), "");
    }

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 5000);
    HttpConnectionParams.setSoTimeout(params, 10000);
    HttpClient client = new DefaultHttpClient(params);
    try {
        String post;
        if (prefs.getString(RegisterDevice.PROPERTY_REG_ID_OLD, null) == null) {
            post = ServerInfo.RESET_SERVER + "/register_device.php?user=" + username + "&deviceid=" + regID
                    + "&devicename=" + URLEncoder.encode(device, "utf-8") + "&version=" + version;
        } else {
            post = ServerInfo.RESET_SERVER + "/update_device_id.php?dev_id="
                    + prefs.getString(PROPERTY_REG_ID_OLD, "") + "&dev_id_new="
                    + prefs.getString(PROPERTY_REG_ID, "");
        }
        HttpPost httpPost = new HttpPost(post);
        HttpEntity localHttpEntity = client.execute(httpPost).getEntity();
        if (localHttpEntity != null) {
            int res = Integer
                    .valueOf(new BufferedReader(new InputStreamReader(localHttpEntity.getContent(), "UTF-8"))
                            .readLine());
            prefs.edit().putBoolean(mContext.getString(R.string.register_complete), true).commit();
            return res != -1;
        }
    } catch (HttpHostConnectException e) {
        return false;
    } catch (IOException localIOException) {
        return false;
    }
    return true;
}

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

private void updateDestinationAccountSelector() {
    AccountManager accountManager = AccountManager.get(this);
    Account[] accounts = accountManager.getAccountsByType(Constants.ACCOUNT_TYPE);
    accountAvailable = false;/*w w w  .j  a  v a 2s .  com*/
    boolean clearAdapter = true;
    accountName = null;
    if (accounts.length > 0) {
        accountAvailable = true;
        if (accounts.length > 1) {
            // Account-Name Auswahl anzeigen
            clearAdapter = false;
            String[] names = new String[accounts.length];
            boolean changed = false;
            int oldCount = destAccountAdapter.getCount();
            for (int i = 0; i < accounts.length; i++) {
                names[i] = accounts[i].name;
                if (i >= oldCount || !destAccountAdapter.getItem(i).equals(names[i])) {
                    changed = true;
                }
            }
            if (changed) {
                destAccountAdapter.setNotifyOnChange(false);
                destAccountAdapter.clear();
                for (String name : names) {
                    destAccountAdapter.add(name);
                }
                destAccountAdapter.setNotifyOnChange(true);
                destAccountAdapter.notifyDataSetChanged();
            }
        } else {
            accountName = accounts[0].name;
        }
    }
    if (clearAdapter) {
        destAccountAdapter.clear();
    }
}

From source file:sg.macbuntu.android.pushcontacts.DeviceRegistrar.java

private static HttpResponse makeRequestNoRetry(Context context, String deviceRegistrationID, String url,
        boolean newToken) throws Exception {
    // Get chosen user account
    SharedPreferences settings = Prefs.get(context);
    String accountName = settings.getString("accountName", null);
    if (accountName == null)
        throw new Exception("No account");

    // Get auth token for account
    Account account = new Account(accountName, "com.google");
    String authToken = getAuthToken(context, account);
    if (authToken == null) {
        throw new PendingAuthException(accountName);
    }/*from w  w w  .j  av a 2s .com*/
    if (newToken) {
        // Invalidate the cached token
        AccountManager accountManager = AccountManager.get(context);
        accountManager.invalidateAuthToken(account.type, authToken);
        authToken = getAuthToken(context, account);
    }

    // Register device with server
    DefaultHttpClient client = new DefaultHttpClient();
    String continueURL = url + "?devregid=" + deviceRegistrationID;
    URI uri = new URI(AUTH_URL + "?continue=" + URLEncoder.encode(continueURL, "UTF-8") + "&auth=" + authToken);
    HttpGet method = new HttpGet(uri);
    HttpResponse res = client.execute(method);
    return res;
}

From source file:org.gege.caldavsyncadapter.authenticator.AuthenticatorActivity.java

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

    mAccountManager = AccountManager.get(this);

    setContentView(R.layout.activity_authenticator);

    // Set up the login form.
    mUser = getIntent().getStringExtra(EXTRA_EMAIL);
    mUserView = (EditText) findViewById(R.id.user);
    mUserView.setText(mUser);//  ww  w. j ava  2s  .com

    mContext = getBaseContext();

    mPasswordView = (EditText) findViewById(R.id.password);
    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
                attemptLogin();
                return true;
            }
            return false;
        }
    });

    mURLView = (EditText) findViewById(R.id.url);

    mLoginFormView = findViewById(R.id.login_form);
    mLoginStatusView = findViewById(R.id.login_status);
    mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

    findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            attemptLogin();
        }
    });

}

From source file:com.flowzr.budget.holo.export.flowzr.FlowzrSyncTask.java

protected Object work(Context context, DatabaseAdapter dba, String... params) throws ImportExportException {

    AccountManager accountManager = AccountManager.get(context);
    android.accounts.Account[] accounts = accountManager.getAccountsByType("com.google");

    String accountName = MyPreferences.getFlowzrAccount(context);
    if (accountName == null) {
        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notificationIntent = new Intent(context, FlowzrSyncActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        Builder mNotifyBuilder = new NotificationCompat.Builder(context);
        mNotifyBuilder.setContentIntent(contentIntent).setSmallIcon(R.drawable.icon)
                .setWhen(System.currentTimeMillis()).setAutoCancel(true)
                .setContentTitle(context.getString(R.string.flowzr_sync))
                .setContentText(context.getString(R.string.flowzr_choose_account));
        nm.notify(0, mNotifyBuilder.build());
        Log.i("Financisto", "account name is null");
        throw new ImportExportException(R.string.flowzr_choose_account);
    }// w w  w  .j av  a 2  s  . c  om
    Account useCredential = null;
    for (int i = 0; i < accounts.length; i++) {
        if (accountName.equals(((android.accounts.Account) accounts[i]).name)) {
            useCredential = accounts[i];
        }
    }
    accountManager.getAuthToken(useCredential, "ah", false, new GetAuthTokenCallback(), null);
    return null;
}

From source file:com.sefford.beauthentic.services.RegistrationIntentService.java

/**
 * Persist registration to third-party servers.
 * <p/>/* ww w  . j a v a2 s.c  om*/
 * Modify this method to associate the user's GCM registration token with any server-side account
 * maintained by your application.
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(final String token) {
    final Account primaryAccount = Sessions.getPrimaryPhoneAccount(AccountManager.get(getApplicationContext()));
    if (primaryAccount != null) {
        final Firebase firebase = new Firebase(Constants.FIREBASE_USER_URL + Hasher.hash(primaryAccount.name));
        final Firebase devices = firebase.child("devices");
        devices.addListenerForSingleValueEvent(new ValueEventListenerAdapter() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                if (!snapshot.exists()) {
                    devices.setValue(Arrays.asList(token));
                } else {
                    List<String> firebaseDevices = (List<String>) snapshot.getValue();
                    if (!firebaseDevices.contains(token)) {
                        firebaseDevices.add(token);
                        devices.setValue(firebaseDevices);
                    }
                }
            }
        });
    }
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.services.ChannelService.java

private static String getGCMRegId(Context ctx) {
    if (!checkPlayServices(ctx)) {
        return "";
    }//from   w w w  .j a va 2  s.c  om

    gcm = GoogleCloudMessaging.getInstance(ctx);
    String regId = getRegistrationId(ctx);

    if (regId.isEmpty()) {
        String senderId = ctx.getResources().getString(R.string.gcm_sender_id);
        try {
            regId = gcm.register(senderId);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }

        // Store gcm register id
        Account ac = AccountUtils.getAccount(ctx, false);
        if (ac == null) {
            log.warn("Cannot get account");
        }
        AccountManager am = AccountManager.get(ctx);
        am.setUserData(ac, JsonKeys.GCM_ID, regId);
    }

    return regId;
}

From source file:com.hemou.android.account.AccountUtils.java

public static UsrSelfDTO getMyInfo(Context ctx) {
    Account acnt = getAccount(ctx);/*from www  .j  a  v a  2 s.  com*/
    if (acnt == null)
        return null;
    String usrStr = AccountManager.get(ctx).getUserData(acnt, Intents.EXTRA.USER);
    if (StrUtils.isEmpties(usrStr))
        return null;
    return StrUtils.str2Obj(usrStr, UsrSelfDTO.class);
}