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:com.google.cloud.solutions.smashpix.MainActivity.java

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

  createImageStorageDirectory();// w  w  w . jav  a  2 s.  c  o m
  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  Logger.getLogger(LOGGER_NAME).setLevel(Constants.LOGGING_LEVEL);

  AccountManager accountManager = AccountManager.get(this);
  Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE);
  accountName = accounts[0].name;

  credential =
      GoogleAccountCredential.usingAudience(this, AUDIENCE_NAMESPACE + Constants.WEB_CLIENT_ID);
  credential.setSelectedAccountName(accountName);
  Image.Builder builder = new Image.Builder(
    AndroidHttp.newCompatibleTransport(),
    new GsonFactory(),
    credential);
  builder.setApplicationName(Constants.APP_NAME);
  service = builder.build();

  listImages();
}

From source file:at.bitfire.davdroid.DavService.java

@SuppressLint("MissingPermission")
void cleanupAccounts() {
    App.log.info("Cleaning up orphaned accounts");

    final OpenHelper dbHelper = new OpenHelper(this);
    try {//from  w  w  w .ja va  2 s .c om
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        List<String> sqlAccountNames = new LinkedList<>();
        AccountManager am = AccountManager.get(this);
        for (Account account : am.getAccountsByType(Constants.ACCOUNT_TYPE))
            sqlAccountNames.add(DatabaseUtils.sqlEscapeString(account.name));

        if (sqlAccountNames.isEmpty())
            db.delete(Services._TABLE, null, null);
        else
            db.delete(Services._TABLE,
                    Services.ACCOUNT_NAME + " NOT IN (" + TextUtils.join(",", sqlAccountNames) + ")", null);
    } finally {
        dbHelper.close();
    }
}

From source file:org.jorge.lolin1.func.chat.ChatIntentService.java

private Boolean login(String upperCaseRealm) {
    ChatServer chatServer;// w ww  . j a  v a  2  s  .c o m
    switch (upperCaseRealm) {
    case "NA":
        chatServer = ChatServer.NA;
        break;
    case "EUW":
        chatServer = ChatServer.EUW;
        break;
    case "EUNE":
        chatServer = ChatServer.EUNE;
        break;
    case "TR":
        chatServer = ChatServer.TR;
        break;
    case "BR":
        chatServer = ChatServer.BR;
        break;
    case "OCE":
        chatServer = ChatServer.OCE;
        break;
    case "LAN":
        chatServer = ChatServer.LAN;
        break;
    case "LAS":
        chatServer = ChatServer.LAS;
        break;
    case "KR":
        chatServer = ChatServer.KR;
        break;
    case "RU":
        chatServer = ChatServer.RU;
        break;
    default:
        throw new IllegalArgumentException("Region " + upperCaseRealm + " not yet implemented");
    }
    try {
        logString("debug", "Assigning api...");
        api = new LoLChat(chatServer, Boolean.FALSE);
    } catch (IOException e) {
        logString("debug", "Exception when constructing the object!");
        e.printStackTrace(System.err);
        if (!(e instanceof SSLException)) {
            launchBroadcastLoginUnsuccessful();
        }
        return Boolean.FALSE;
    }
    final AccountManager accountManager = AccountManager.get(getApplicationContext());
    Account[] accounts = accountManager
            .getAccountsByType(LoLin1Utils.getString(getApplicationContext(), "account_type", null));
    Account thisRealmAccount = null;
    for (Account acc : accounts) {
        if (acc.name.contentEquals(upperCaseRealm)) {
            thisRealmAccount = acc;
            break;
        }
    }
    if (thisRealmAccount == null) {
        return Boolean.FALSE;//There's no account associated to this realm
    }
    AsyncTask<Account, Void, String[]> credentialsTask = new AsyncTask<Account, Void, String[]>() {
        @Override
        protected String[] doInBackground(Account... params) {
            String[] processedAuthToken = null;
            try {
                processedAuthToken = accountManager.blockingGetAuthToken(params[0], "none", Boolean.TRUE)
                        .split(AccountAuthenticator.TOKEN_GENERATION_JOINT);
            } catch (OperationCanceledException | IOException | AuthenticatorException e) {
                Crashlytics.logException(e);
            }
            return processedAuthToken;
        }
    };
    //It's necessary to run the task in an executor because the main one is already full and if we add this one a livelock will occur
    ExecutorService loginExecutor = Executors.newFixedThreadPool(1);
    credentialsTask.executeOnExecutor(loginExecutor, thisRealmAccount);
    String[] processedAuthToken = new String[0];
    try {
        processedAuthToken = credentialsTask.get();
    } catch (InterruptedException | ExecutionException e) {
        Crashlytics.logException(e);
    }
    Boolean loginSuccess = Boolean.FALSE;
    try {
        loginSuccess = api.login(processedAuthToken[0], processedAuthToken[1]);
    } catch (IOException e) {
        Crashlytics.logException(e);
    }
    if (loginSuccess) {
        api.reloadRoster();
        isConnected = Boolean.TRUE;
        return Boolean.TRUE;
    } else {
        isConnected = Boolean.FALSE;
        return Boolean.FALSE;
    }
}

From source file:com.myandroidremote.AccountsActivity.java

/**
 * Registers for C2DM messaging with the given account name.
 * //from   w ww . j a v a 2s.c o m
 * @param accountName
 *            a String containing a Google account name
 */
private void register(final String accountName) {
    // Store the account name in shared preferences
    final SharedPreferences prefs = Util.getSharedPreferences(mContext);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(Util.ACCOUNT_NAME, accountName);
    editor.putString(Util.AUTH_COOKIE, null);
    editor.commit();

    // Obtain an auth token and register
    final AccountManager mgr = AccountManager.get(mContext);
    Account[] accts = mgr.getAccountsByType("com.google");
    for (Account acct : accts) {
        if (acct.name.equals(accountName)) {
            if (Util.isDebug(mContext)) {
                // Use a fake cookie for the dev mode app engine server
                // The cookie has the form email:isAdmin:userId
                // We set the userId to be the same as the account name
                String authCookie = "dev_appserver_login=" + accountName + ":false:" + accountName;
                boolean result = prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit();
                C2DMessaging.register(mContext, Setup.SENDER_ID);
            } else {
                // Get the auth token from the AccountManager and convert
                // it into a cookie for the appengine server
                mgr.getAuthToken(acct, "ah", null, this, new AccountManagerCallback<Bundle>() {
                    public void run(AccountManagerFuture<Bundle> future) {
                        try {
                            Bundle authTokenBundle = future.getResult();
                            String authToken = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();
                            String authCookie = getAuthCookie(authToken);
                            if (authCookie == null) {
                                mgr.invalidateAuthToken("com.google", authToken);
                            }
                            prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit();

                            C2DMessaging.register(mContext, Setup.SENDER_ID);
                        } catch (AuthenticatorException e) {
                            Log.w(TAG, "Got AuthenticatorException " + e);
                            Log.w(TAG, Log.getStackTraceString(e));
                        } catch (IOException e) {
                            Log.w(TAG, "Got IOException " + Log.getStackTraceString(e));
                            Log.w(TAG, Log.getStackTraceString(e));
                        } catch (OperationCanceledException e) {
                            Log.w(TAG, "Got OperationCanceledException " + e);
                            Log.w(TAG, Log.getStackTraceString(e));
                        }
                    }
                }, null);
            }
            break;
        }
    }
}

From source file:com.gmail.nagamatu.radiko.installer.RadikoInstallerActivity.java

private void getEmailAndPasswd() {
    final AccountManager am = AccountManager.get(this);
    mAccounts = am.getAccountsByType("com.google");
    mAccount = null;//from   w  w w.j a  va  2s  .c  o m

    switch (mAccounts.length) {
    case 0:
        updateMessage(R.string.error_download, getResources().getString(R.string.no_google_account));
        break;
    case 1:
        mAccount = mAccounts[0];
        showDialog(DIALOG_PASSWD);
        break;
    default:
        showDialog(DIALOG_SELECT_ACCOUNT);
        break;
    }
}

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

protected void restoreUIFromPref() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    lastSyncLocalTimestamp = MyPreferences.getFlowzrLastSync(getApplicationContext());
    preferences.getLong(FlowzrSyncOptions.PROPERTY_LAST_SYNC_TIMESTAMP, 0);
    AccountManager accountManager = AccountManager.get(getApplicationContext());
    Account[] accounts = accountManager.getAccountsByType("com.google");
    for (Account account : accounts) {
        if (preferences.getString(FlowzrSyncOptions.PROPERTY_USE_CREDENTIAL, "").equals(account.name)) {
            useCredential = account;/*from  www .j  a v  a 2 s  .com*/
        }
    }
    TextView tv = (TextView) findViewById(R.id.sync_was);
    tv.setText(getString(R.string.flowzr_sync_was) + " " + new Date(lastSyncLocalTimestamp).toLocaleString());

}

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

protected void restoreUIFromPref() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    lastSyncLocalTimestamp = preferences.getLong(FlowzrSyncOptions.PROPERTY_LAST_SYNC_TIMESTAMP, 0);
    AccountManager accountManager = AccountManager.get(getApplicationContext());
    Account[] accounts = accountManager.getAccountsByType("com.google");
    for (Account account : accounts) {
        if (preferences.getString(FlowzrSyncOptions.PROPERTY_USE_CREDENTIAL, "").equals(account.name)) {
            useCredential = account;//from   w  w  w . j a  va  2s .c  o m
        }
    }
    TextView tv = (TextView) findViewById(R.id.sync_was);
    tv.setText(getString(R.string.flowzr_sync_was) + " " + new Date(lastSyncLocalTimestamp).toLocaleString());
}

From source file:com.meiste.greg.ptw.GAE.java

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private boolean reconnect() {
    final AccountManager mgr = AccountManager.get(mContext);
    final Account[] accts = mgr.getAccountsByType(ACCOUNT_TYPE);
    for (final Account acct : accts) {
        if (acct.name.equals(mAccountName)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                mgr.getAuthToken(acct, "ah", null, false, new AuthTokenCallback(), null);
            } else {
                mgr.getAuthToken(acct, "ah", false, new AuthTokenCallback(), null);
            }/*www  . j  av a  2s  .  c om*/
            return true;
        }
    }
    Util.log("Account " + mAccountName + " not found!");
    return false;
}

From source file:eu.masconsult.bgbanking.activity.HomeActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    MenuItem refreshItem = menu.add(R.string.menu_item_refresh);
    refreshItem.setIcon(R.drawable.ic_menu_refresh);
    refreshItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
    refreshItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override//from w  w  w .j a v  a2 s  . c  o  m
        public boolean onMenuItemClick(MenuItem item) {
            AccountManager accountManager = AccountManager.get(HomeActivity.this);
            if (accountManager == null) {
                return false;
            }

            long cnt = 0;
            Bank[] banks = Bank.values();
            for (Bank bank : banks) {
                for (Account account : accountManager
                        .getAccountsByType(bank.getAccountType(HomeActivity.this))) {
                    Log.v(TAG, String.format("account: %s, %s, %s", account.name, account.type,
                            ContentResolver.getIsSyncable(account, BankingContract.AUTHORITY)));
                    Bundle bundle = new Bundle();
                    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
                    ContentResolver.requestSync(account, BankingContract.AUTHORITY, bundle);
                    cnt++;
                }
            }

            EasyTracker.getTracker().trackEvent("ui_action", "menu_item_click", "refresh", cnt);
            return true;
        }
    });

    MenuItem addAccountItem = menu.add(R.string.menu_item_add_account);
    addAccountItem.setIcon(R.drawable.ic_menu_add);
    addAccountItem
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
    addAccountItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            addAccount();
            EasyTracker.getTracker().trackEvent("ui_action", "menu_item_click", "add_account", 1l);
            return true;
        }
    });

    MenuItem sendFeedback = menu.add(R.string.menu_item_send_feedback);
    sendFeedback.setIcon(R.drawable.ic_menu_start_conversation);
    sendFeedback.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    sendFeedback.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            PackageInfo manager;
            try {
                manager = getPackageManager().getPackageInfo(getPackageName(), 0);
            } catch (NameNotFoundException e) {
                manager = new PackageInfo();
                manager.versionCode = 0;
                manager.versionName = "undef";
            }
            try {
                startActivity(new Intent(Intent.ACTION_SEND).setType("plain/text")
                        .putExtra(Intent.EXTRA_EMAIL, new String[] { "bgbanks@masconsult.eu" })
                        .putExtra(Intent.EXTRA_SUBJECT,
                                "BG Banks v" + manager.versionName + "-" + manager.versionCode + " feedback"));
                EasyTracker.getTracker().trackEvent("ui_action", "menu_item_click", "send_feedback", 1l);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            return true;
        }
    });

    return true;
}

From source file:net.heroicefforts.viable.android.rep.it.GIssueTrackerRepository.java

private void manageAccount() {
    AccountManager accMgr = (AccountManager) act.getSystemService(Context.ACCOUNT_SERVICE);
    if (Config.LOGD)
        Log.d(TAG, "Requesting account creation.");
    Account[] accts = accMgr.getAccountsByType(GCLAccountAuthenticator.ACCT_TYPE);
    if (accts.length > 0)
        accMgr.confirmCredentials(accts[0], null, act, callback, null);
    else/*from ww  w .  java2  s. c om*/
        accMgr.addAccount(GCLAccountAuthenticator.ACCT_TYPE, GCLAccountAuthenticator.TOKEN_TYPE_ISSUE_TRACKER,
                null, null, act, callback, null);
}