Example usage for android.accounts AccountManager getAccountsByType

List of usage examples for android.accounts AccountManager getAccountsByType

Introduction

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

Prototype

@NonNull
public Account[] getAccountsByType(String type) 

Source Link

Document

Lists all accounts of particular type visible to the caller.

Usage

From source file:ru.orangesoftware.financisto2.activity.FlowzrSyncActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FlowzrSyncActivity.me = this;
    mNotifyBuilder = new NotificationCompat.Builder(getApplicationContext());
    nm = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    setContentView(R.layout.flowzr_sync);
    restoreUIFromPref();/*from   w w w .  j a va  2s. c o m*/
    if (useCredential != null) {

    }

    AccountManager accountManager = AccountManager.get(getApplicationContext());
    final Account[] accounts = accountManager.getAccountsByType("com.google");
    if (accounts.length < 1) {
        new AlertDialog.Builder(this).setTitle(getString(R.string.flowzr_sync_error))
                .setMessage(R.string.account_required)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                }).show();
    }
    //radio crendentials
    RadioGroup radioGroupCredentials = (RadioGroup) findViewById(R.id.radioCredentials);
    OnClickListener radio_listener = new OnClickListener() {
        public void onClick(View v) {
            RadioButton radioButtonSelected = (RadioButton) findViewById(v.getId());
            for (Account account : accounts) {
                if (account.name == radioButtonSelected.getText()) {
                    useCredential = account;
                }
            }
        }
    };
    //initialize value
    for (int i = 0; i < accounts.length; i++) {
        RadioButton rb = new RadioButton(this);
        radioGroupCredentials.addView(rb); //, 0, lp); 
        rb.setOnClickListener(radio_listener);
        rb.setText(((Account) accounts[i]).name);
        if (useCredential != null) {
            if (accounts[i].name.equals(useCredential.name)) {
                rb.toggle(); //.setChecked(true);
            }
        }
    }

    bOk = (Button) findViewById(R.id.bOK);
    bOk.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

            setRunning();
            initProgressDialog();
            //                if (useCredential!=null) {
            //                   flowzrBilling=new FlowzrBilling(FlowzrSyncActivity.this, getApplicationContext(), http_client, useCredential.toString());  
            //                }               
            if (useCredential == null) {
                showErrorPopup(FlowzrSyncActivity.this, R.string.flowzr_choose_account);
                notifyUser(getString(R.string.flowzr_choose_account), 100);
                setReady();
            } else if (!isOnline(FlowzrSyncActivity.this)) {
                showErrorPopup(FlowzrSyncActivity.this, R.string.flowzr_sync_error_no_network);
                notifyUser(getString(R.string.flowzr_sync_error_no_network), 100);
                setReady();
            } else {
                saveOptionsFromUI();
                //Play Service Billing
                //FlowzrBilling flowzrBilling = new FlowzrBilling(FlowzrSyncActivity.this, getApplicationContext(), http_client, useCredential.toString());  
                //if (flowzrSyncTask.checkSubscription()) {
                flowzrSyncEngine = new FlowzrSyncEngine(FlowzrSyncActivity.this);
                //}

            }
        }
    });

    Button bCancel = (Button) findViewById(R.id.bCancel);
    bCancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            if (flowzrSyncEngine != null) {
                flowzrSyncEngine.isCanceled = true;
            }
            isRunning = false;
            setResult(RESULT_CANCELED);
            setReady();
            startActivity(new Intent(getApplicationContext(), MainActivity.class));
            //finish();
        }
    });

    Button textViewAbout = (Button) findViewById(R.id.buySubscription);
    textViewAbout.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (isOnline(FlowzrSyncActivity.this)) {
                visitFlowzr(useCredential);
            } else {
                showErrorPopup(FlowzrSyncActivity.this, R.string.flowzr_sync_error_no_network);
            }
        }
    });

    Button textViewAboutAnon = (Button) findViewById(R.id.visitFlowzr);
    textViewAboutAnon.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (isOnline(FlowzrSyncActivity.this)) {
                visitFlowzr(null);
            } else {
                showErrorPopup(FlowzrSyncActivity.this, R.string.flowzr_sync_error_no_network);
            }
        }
    });

    TextView textViewNotes = (TextView) findViewById(R.id.flowzrPleaseNote);
    textViewNotes.setMovementMethod(LinkMovementMethod.getInstance());
    textViewNotes.setText(Html.fromHtml(getString(R.string.flowzr_terms_of_use)));
    if (MyPreferences.isAutoSync(this)) {
        if (checkPlayServices()) {
            gcm = GoogleCloudMessaging.getInstance(this);
            regid = getRegistrationId(getApplicationContext());

            if (regid.equals("")) {
                registerInBackground();
            }
            Log.i(TAG, "Google Cloud Messaging registered as :" + regid);
        } else {
            Log.i(TAG, "No valid Google Play Services APK found.");
        }
    }
}

From source file:com.monkey.entonado.MainActivity.java

/**
 * Realiza la conexion al servidor//from   ww  w .ja  va2  s  .  c  om
 * @return mensaje Indica si la conexion fue exitosa
 */
@SuppressLint("NewApi")
public String conectar() {
    intentoConectar = true;
    try {
        System.out.println("Conectado en 4 ");
        canal = new Socket();
        /**
         * Create a client socket with the host,
         * port, and timeout information.
         */
        System.out.println("Conectado en 3");
        canal.bind(null);
        System.out.println("Conectado en 2");
        canal.connect((new InetSocketAddress(ip, 10052)));
        System.out.println("Conectado en 1");
        out = new PrintWriter(canal.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(canal.getInputStream()));

        String info = "";

        AccountManager aManager = AccountManager.get(this);
        Account[] accounts = aManager.getAccountsByType("com.google");

        for (Account account : accounts) {
            String accountId = account.name;
            info += accountId + " : ";
        }

        out.println(INFO_USUARIO + ";" + "U:" + info);

        String mens = in.readLine();

        System.out.println("Estas conectado! " + mens + " : " + canal.getInetAddress());
        mensajeConexion = "Estas conectado!";
        return "Estas Conectado!";
    } catch (SocketException e) {
        System.out.println("No se establecio la conexion");
        mensajeConexion = "No se estableci la conexin: " + e.getMessage();
        return "No se establecio la conexin";
    } catch (Exception e) {
        System.out.println("No se establecio la conexion");
        mensajeConexion = "No se estableci la conexin: " + e.getMessage();
        return "No se establecio la conexin";
    }
}

From source file:git.egatuts.nxtremotecontroller.fragment.OnlineControllerFragment.java

public String getOwnerEmail() {
    AccountManager manager = AccountManager.get(this.getActivity());
    Account[] accounts = manager.getAccountsByType("com.google");
    return accounts[0].name;
}

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

/**
 * Removes an account. This should be called when, e.g., the user changes
 * to a new server./* w w  w  .ja v a  2 s  . c  om*/
 * @param context
 * @param accountType
 */
public static void removeAccount(Context context, String accountType) {
    AccountManager am = AccountManager.get(context);
    am.invalidateAuthToken(accountType, SyncAdapter.AUTHTOKEN_TYPE);
    Account[] accounts = am.getAccountsByType(accountType);
    if (accounts.length != 0)
        am.removeAccount(accounts[0], null, null);
    //String authkey = getAuthKey(context);
    //return authkey == null;
}

From source file:com.nextgis.mobile.fragment.LayersFragment.java

protected void setupSyncOptions() {
    mAccounts.clear();//from www .jav  a2  s  . c  o  m
    final AccountManager accountManager = AccountManager.get(getActivity().getApplicationContext());
    Log.d(TAG, "LayersFragment: AccountManager.get(" + getActivity().getApplicationContext() + ")");
    final IGISApplication application = (IGISApplication) getActivity().getApplication();
    List<INGWLayer> layers = new ArrayList<>();

    for (Account account : accountManager.getAccountsByType(NGW_ACCOUNT_TYPE)) {
        layers.clear();
        MapContentProviderHelper.getLayersByAccount(application.getMap(), account.name, layers);

        if (layers.size() > 0)
            mAccounts.add(account);
    }

    if (mAccounts.isEmpty()) {
        if (null != mSyncButton) {
            mSyncButton.setEnabled(false);
            mSyncButton.setVisibility(View.GONE);
        }
        if (null != mInfoText) {
            mInfoText.setVisibility(View.INVISIBLE);
        }
    } else {
        if (null != mSyncButton) {
            mSyncButton.setVisibility(View.VISIBLE);
            mSyncButton.setEnabled(true);
            mSyncButton.setOnClickListener(this);
        }
        if (null != mInfoText) {
            mInfoText.setVisibility(View.VISIBLE);
        }
    }
}

From source file:com.mobilyzer.AccountSelector.java

/** Starts an authentication request  */
public void authenticate() throws OperationCanceledException, AuthenticatorException, IOException {
    Logger.i("AccountSelector.authenticate() running");
    /* We only need to authenticate every AUTHENTICATE_PERIOD_MILLI milliseconds, during
     * which we can reuse the cookie. If authentication fails due to expired
     * authToken, the client of AccountSelector can call authImmedately() to request
     * authenticate() upon the next checkin
     *//*from   w  ww  .j a  v a  2 s . c o  m*/
    long authTimeLast = this.getLastAuthTime();
    long timeSinceLastAuth = System.currentTimeMillis() - authTimeLast;
    if (!this.shouldAuthImmediately() && authTimeLast != 0 && (timeSinceLastAuth < AUTHENTICATE_PERIOD_MSEC)) {
        return;
    }

    Logger.i("Authenticating. Last authentication is " + timeSinceLastAuth / 1000 / 60 + " minutes ago. ");

    AccountManager accountManager = AccountManager.get(context.getApplicationContext());
    if (this.authToken != null) {
        // There will be no effect on the token if it is still valid
        Logger.i("Invalidating token");
        accountManager.invalidateAuthToken(ACCOUNT_TYPE, this.authToken);
    }
    if (!hasGetAccountsPermission(context)) {
        isAnonymous = true;
        return;
    }

    Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE);
    Logger.i("Got " + accounts.length + " accounts");

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
    String selectedAccount = prefs.getString(Config.PREF_KEY_SELECTED_ACCOUNT, null);
    Logger.i("Selected account = " + selectedAccount);

    final String defaultUserName = Config.DEFAULT_USER;
    isAnonymous = true;
    if (selectedAccount != null && selectedAccount.equals(defaultUserName)) {
        return;
    }

    if (accounts != null && accounts.length > 0) {
        // Default account should be the Anonymous account
        Account accountToUse = new Account(Config.DEFAULT_USER, ACCOUNT_TYPE);
        if (!accounts[accounts.length - 1].name.equals(defaultUserName)) {
            for (Account account : accounts) {
                if (account.name.equals(defaultUserName)) {
                    accountToUse = account;
                    break;
                }
            }
        }
        if (selectedAccount != null) {
            for (Account account : accounts) {
                if (account.name.equals(selectedAccount)) {
                    accountToUse = account;
                    break;
                }
            }
        }

        isAnonymous = accountToUse.name.equals(defaultUserName);

        if (isAnonymous) {
            Logger.d("Skipping authentication as account is " + defaultUserName);
            return;
        }

        Logger.i("Trying to get auth token for " + accountToUse);
        AccountManagerFuture<Bundle> future = accountManager.getAuthToken(accountToUse, "ah", false,
                new AccountManagerCallback<Bundle>() {
                    @Override
                    public void run(AccountManagerFuture<Bundle> result) {
                        Logger.i("AccountManagerCallback invoked");
                        try {
                            getAuthToken(result);
                        } catch (RuntimeException e) {
                            Logger.e("Failed to get authToken", e);
                            /* TODO(Wenjie): May ask the user whether to quit the app nicely here if a number
                             * of trials have been made and failed. Since Speedometer is basically useless 
                             * without checkin
                             */
                        }
                    }
                }, null);
        Logger.i("AccountManager.getAuthToken returned " + future);
    } else {
        throw new RuntimeException("No google account found");
    }
}

From source file:com.kiddobloom.bucketlist.AuthenticatorActivity.java

@Override
public void onCompleted(GraphUser user, Response response) {
    // TODO Auto-generated method stub
    //Log.d("tagaa", "FacebookGetMe: oncomplete me request");

    if (response != null) {

        FacebookRequestError error = response.getError();
        if (error != null) {
            // failed to get user info from facebook - TOAST
            //Log.d("tagaa", "FacebookGetMe: failed to get user info from facebook: " + error);

            Toast.makeText(getApplicationContext(),
                    "Failed to retrieve information from Facebook - OFFLINE mode", Toast.LENGTH_SHORT).show();

            saveState(StateMachine.OFFLINE_STATE);
            saveStatus(StateMachine.ERROR_STATUS);
            saveError(StateMachine.FB_GET_ME_FAILED_ERROR);
            goToBucketListActivity();/*from  w ww  . j  a va 2s  .  c o  m*/
            return;
        }
    }

    if (user != null) {

        boolean registered = false;
        final Account account;

        // if we get to this point, we know that the network is OK
        // we can continue server registration

        //Log.d("tagaa", "FacebookGetMe: me = " + user);

        // check whether (com.kidobloom) type account has been created for the fb-userid
        // if account db is empty - create a new account using the fb-userid
        // else if an account already exists, check to see if it matches the current fb-userid
        // if account exists and matches the fb-userid, do nothing
        // otherwise replace the account with the new fb-userid
        AccountManager accountManager = AccountManager.get(getApplicationContext());
        Account[] accounts = accountManager.getAccountsByType("com.kiddobloom");

        if (accounts.length <= 0) {
            //Log.d("tagaa", "FacebookGetMe: no account exists");
            // create a new account
            account = new Account(user.getId(), Constants.ACCOUNT_TYPE);
            am.addAccountExplicitly(account, null, null);
            ContentResolver.setSyncAutomatically(account, MyContentProvider.AUTHORITY, true);
            registered = false;
        } else {
            // get the first account
            //Log.d("tagaa", "FacebookGetMe: account = " + accounts[0].name);

            if (accounts[0].name.equals(user.getId())) {
                registered = true;
                //Log.d("tagaa", "FacebookGetMe: account for facebookId = " + user.getId() + " already created");
            } else {
                //Log.d("tag", "FacebookGetMe: user switched account");
                // remove the account first
                am.removeAccount(accounts[0], null, null);

                // add new account with the new facebook userid
                account = new Account(user.getId(), Constants.ACCOUNT_TYPE);
                am.addAccountExplicitly(account, null, null);
                ContentResolver.setSyncAutomatically(account, MyContentProvider.AUTHORITY, true);

                // update the registered flag so facebook ID gets re-registered
                registered = false;
            }
        }

        // at this point, an account should already be created
        // store the userid and registered boolean in preferences db
        saveFbUserId(user.getId());
        saveUserIdRegistered(registered);

        saveState(StateMachine.FB_GET_FRIENDS_STATE);
        saveStatus(StateMachine.TRANSACTING_STATUS);
        saveError(StateMachine.NO_ERROR);

        // request facebook friends list
        Request.executeMyFriendsRequestAsync(response.getRequest().getSession(), this);

    } else {
        // throw an exception here - facebook does not indicate error but user is null 
        //Log.d("tagaa", "FacebookGetMe: failed to get user info from facebook - OFFLINE mode");

        Toast.makeText(getApplicationContext(), "Failed to retrieve information from Facebook",
                Toast.LENGTH_SHORT).show();

        saveState(StateMachine.OFFLINE_STATE);
        saveStatus(StateMachine.ERROR_STATUS);
        saveError(StateMachine.FB_GET_ME_FAILED_ERROR);
        goToBucketListActivity();
    }
}

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  w ww. j av  a2s. c o  m
    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.mikecorrigan.bohrium.pubsub.RegistrationClient.java

private Account getAccount() {
    final AccountManager mgr = AccountManager.get(this);
    final Account[] accounts = mgr
            .getAccountsByType(mConfiguration.getString(ACCOUNT_TYPE, DEFAULT_ACCOUNT_TYPE));
    for (final Account account : accounts) {
        if (account.name.equals(mConfiguration.getString(ACCOUNT_NAME))) {
            return account;
        }// w  w w.j a  v  a 2s.  c om
    }

    return null;
}