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:org.runbuddy.tomahawk.dialogs.GMusicConfigDialog.java

/**
 * Called when this {@link android.support.v4.app.DialogFragment} is being created
 *///from   w w  w  .ja  v  a 2 s . com
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    mScriptResolver = PipeLine.get().getResolver(TomahawkApp.PLUGINNAME_GMUSIC);

    TextView headerTextView = (TextView) addScrollingViewToFrame(R.layout.config_textview);
    headerTextView.setText(mScriptResolver.getDescription());

    TextView infoTextView = (TextView) addScrollingViewToFrame(R.layout.config_textview);
    infoTextView.setText(R.string.gmusic_info_text);

    String loggedInAccountName = null;
    Map<String, Object> config = mScriptResolver.getConfig();
    if (config.get("email") instanceof String) {
        loggedInAccountName = (String) config.get("email");
    }

    mRadioGroup = (RadioGroup) addScrollingViewToFrame(R.layout.config_radiogroup);
    final AccountManager accountManager = AccountManager.get(TomahawkApp.getContext());
    final Account[] accounts = accountManager.getAccountsByType("com.google");
    mAccountMap = new HashMap<>();
    LayoutInflater inflater = getActivity().getLayoutInflater();
    for (Account account : accounts) {
        RadioButton radioButton = (RadioButton) inflater.inflate(R.layout.config_radiobutton, mRadioGroup,
                false);
        radioButton.setText(account.name);
        mRadioGroup.addView(radioButton);
        mAccountMap.put(radioButton.getId(), account);
        if (loggedInAccountName != null && account.name.equals(loggedInAccountName)) {
            mRadioGroup.check(radioButton.getId());
        }
    }
    showEnableButton(mEnableButtonListener);
    onResolverStateUpdated(mScriptResolver);

    hideNegativeButton();

    setDialogTitle(mScriptResolver.getName());
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(getDialogView());
    return builder.create();
}

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  o m*/
    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.google.sampling.experiential.android.lib.GoogleAccountLoginHelper.java

private Account getGoogleAccount(AccountManager accountManager, String desiredSuffix) {
    for (Account account : accountManager.getAccountsByType(GOOGLE_ACCOUNT_TYPE)) {
        if (account.name.endsWith(desiredSuffix)) {
            return account;
        }/*from w ww .j a  v  a  2  s  .co  m*/
    }
    return null;
}

From source file:fr.unix_experience.owncloud_sms.activities.remote_account.RestoreMessagesActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_restore_messages);

    assert getIntent().getExtras() != null;

    String accountName = getIntent().getExtras().getString("account");

    // accountName cannot be null, devel error
    assert accountName != null;
    AccountManager accountManager = AccountManager.get(getBaseContext());
    Account[] accountList = accountManager.getAccountsByType(getString(R.string.account_type));
    for (Account element : accountList) {
        if (element.name.equals(accountName)) {
            _account = element;/*from  ww w.  j  a v a 2 s. c  o  m*/
        }
    }

    if (_account == null) {
        throw new IllegalStateException(getString(R.string.err_didnt_find_account_restore));
    }

    initInterface();
    Button fix_button = (Button) findViewById(R.id.button_fix_permissions);
    final Button launch_restore = (Button) findViewById(R.id.button_launch_restore);
    final ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar_restore);

    final RestoreMessagesActivity me = this;
    fix_button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
                notifyIncompatibleVersion();
                return;
            }

            if (!new ConnectivityMonitor(me).isValid()) {
                notifyNoConnectivity();
                return;
            }

            Log.i(RestoreMessagesActivity.TAG, "Ask to change the default SMS app");

            Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
            intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getBaseContext().getPackageName());
            startActivityForResult(intent, REQUEST_DEFAULT_SMSAPP);
        }
    });

    launch_restore.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (!new ConnectivityMonitor(me).isValid()) {
                notifyNoConnectivity();
                return;
            }

            launch_restore.setVisibility(View.INVISIBLE);
            pb.setVisibility(View.VISIBLE);

            // Verify connectivity
            Log.i(RestoreMessagesActivity.TAG, "Launching restore asynchronously");
            restoreInProgress = true;
            new ASyncSMSRecovery.SMSRecoveryTask(me, _account).execute();
        }
    });
}

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));
    }/*from   www  .  j  av a 2 s  .c  o  m*/
    return connections;
}

From source file:uk.ac.horizon.aestheticodes.controllers.ExperienceListUpdater.java

private HttpResponse put(String url, String data) throws Exception {
    HttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut(new URL(url).toURI());
    put.addHeader("content-type", "application/json");
    put.setEntity(new StringEntity(data));

    String token = null;/*from   w  w w.ja v  a2s .com*/
    try {
        AccountManager accountManager = AccountManager.get(context);
        Account[] accounts = accountManager.getAccountsByType("com.google");
        if (accounts.length >= 1) {
            Log.i("", "Getting token for " + accounts[0].name);
            token = GoogleAuthUtil.getToken(context, accounts[0].name, context.getString(R.string.app_scope));
            put.addHeader("Authorization", "Bearer " + token);
            Log.i("", token);
        }
    } catch (Exception e) {
        Log.e("", e.getMessage(), e);
    }

    Log.i("", "PUT " + url);
    Log.i("", data);
    HttpResponse response = client.execute(put);
    if (response.getStatusLine().getStatusCode() == 401) {
        Log.w("", "Response " + response.getStatusLine().getStatusCode());
        if (token != null) {
            GoogleAuthUtil.invalidateToken(context, token);
        }
    } else if (response.getStatusLine().getStatusCode() != 200) {
        Log.w("", "Response " + response.getStatusLine().getStatusCode() + ": "
                + response.getStatusLine().getReasonPhrase());
    }

    return response;
}

From source file:de.unclenet.dehabewe.CalendarActivity.java

private void gotAccount(boolean tokenExpired) {
    SharedPreferences settings = getSharedPreferences(PREF, 0);
    String accountName = settings.getString("accountName", null);
    if (accountName != null) {
        AccountManager manager = AccountManager.get(this);
        Account[] accounts = manager.getAccountsByType("com.google");
        int size = accounts.length;
        for (int i = 0; i < size; i++) {
            Account account = accounts[i];
            if (accountName.equals(account.name)) {
                if (tokenExpired) {
                    manager.invalidateAuthToken("com.google", this.authToken);
                }//from   w  w  w.  ja  va2  s  .c o m
                gotAccount(manager, account);
                return;
            }
        }
    }
    showDialog(DIALOG_ACCOUNTS);
}

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

/**
 * Checks for a pending PaymentVerification
 *///from  w  ww.  j  a  va 2  s.  co m
private void checkForPaymentVerification(Context context) {
    AccountManager acm = AccountManager.get(context);
    Account[] accounts = acm.getAccountsByType(Constants.ACCOUNT_TYPE);
    for (Account account : accounts) {
        // Don't verify is already a Verification is in Progress
        if (SyncUtils.isPaymentVerificationStarted()) {
            LogHelper.logD(TAG, "PaymentVerification skipped, because another verifcation is running", null);
            break;
        }

        PaymentData paymentData = SyncUtils.getPayment(account, acm);
        if (paymentData != null) {
            PayPalConfirmationResult result = null;
            try {
                LogHelper.logI(TAG, "PaymentVerification started for account " + account.name);
                String authtoken = NetworkUtilities.blockingGetAuthToken(acm, account, null);
                if (authtoken == null) {
                    continue;
                }
                result = NetworkUtilities.verifyPayPalPayment(context, account, paymentData.priceId.toString(),
                        paymentData.paymentConfirmation.toString(), authtoken, acm);
            } catch (NetworkErrorException e) {
                result = PayPalConfirmationResult.NETWORK_ERROR;
                LogHelper.logWCause(TAG, "Verifying PayPalPayment failed.", e);
            } catch (AuthenticationException e) {
                result = PayPalConfirmationResult.AUTHENTICATION_FAILED;
                LogHelper.logWCause(TAG, "Verifying PayPalPayment failed.", e);
            } catch (OperationCanceledException e) {
                result = PayPalConfirmationResult.AUTHENTICATION_FAILED;
                LogHelper.logD(TAG, "Verifying canceled.", e);
            } catch (ServerException e) {
                result = PayPalConfirmationResult.VERIFIER_ERROR;
                LogHelper.logWCause(TAG, "Verifying PayPalPayment failed.", e);
            }
            if (result != null) {
                processResult(context, acm, account, result);
            }
        }
    }
}

From source file:de.unclenet.dehabewe.CalendarActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_ACCOUNTS:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Select a Google account");
        final AccountManager manager = AccountManager.get(this);
        final Account[] accounts = manager.getAccountsByType("com.google");
        final int size = accounts.length;
        String[] names = new String[size];
        for (int i = 0; i < size; i++) {
            names[i] = accounts[i].name;
        }//from  w  ww .  j  a v a  2s  .com
        builder.setItems(names, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                gotAccount(manager, accounts[which]);
            }
        });
        return builder.create();
    }
    return null;
}

From source file:org.birthdayadapter.util.AccountHelper.java

/**
 * Checks whether the account is enabled or not
 *///from   w ww.ja v  a 2 s  . c o  m
public boolean isAccountActivated() {
    AccountManager am = AccountManager.get(mContext);

    if (ActivityCompat.checkSelfPermission(mContext,
            Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
        return false;
    }
    Account[] availableAccounts = am.getAccountsByType(Constants.ACCOUNT_TYPE);
    for (Account currentAccount : availableAccounts) {
        if (currentAccount.name.equals(Constants.ACCOUNT_NAME)) {
            return true;
        }
    }

    return false;
}