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.export.flowzr.FlowzrSyncEngine.java

public FlowzrSyncEngine(FlowzrSyncActivity a) {
    android.accounts.Account useCredential = null;
    if (a == null) {
        a = (FlowzrSyncActivity) FlowzrSyncActivity.getMySelf();
    }/*ww w  . ja v  a2 s .  c  o  m*/
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(a);
    this.options = FlowzrSyncOptions.fromPrefs(preferences);
    this.context = a;
    this.flowzrSyncActivity = a;
    FlowzrSyncActivity.isRunning = true;
    this.dba = DatabaseAdapter_.getInstance_(context);
    this.db = dba.db();

    if (flowzrSyncActivity == null) {
        Log.i(TAG, "No activity found, creating.");
        Intent intent = new Intent(context, FlowzrSyncActivity.class);
        context.startActivity(intent);
        return;
    }

    http_client = new DefaultHttpClient();

    if (options.appVersion == null) {
        try {
            options.appVersion = context.getPackageManager().getPackageInfo(context.getPackageName(),
                    0).versionName;
        } catch (NameNotFoundException e) {
            options.appVersion = "undef";
            e.printStackTrace();
        }
    }
    Log.i(TAG, "init sync engine, last sync was " + new Date(FlowzrSyncOptions.last_sync_ts).toLocaleString());

    AccountManager accountManager = AccountManager.get(context);
    android.accounts.Account[] accounts = accountManager.getAccountsByType("com.google");
    for (int i = 0; i < accounts.length; i++) {
        if (preferences.getString(FlowzrSyncOptions.PROPERTY_USE_CREDENTIAL, "")
                .equals(((android.accounts.Account) accounts[i]).name)) {
            useCredential = accounts[i];
        }
    }
    if (useCredential != null) {
        AccountManager.get(context).getAuthToken(useCredential, "ah", null, flowzrSyncActivity,
                new GetAuthTokenCallback(), null);
    } else {
        Log.e(TAG, "No account selected");
    }
}

From source file:com.android.tv.settings.MainFragment.java

private void updateAccounts() {
    if (mAccountsGroup == null) {
        return;/*from ww  w .j ava2 s.  c o m*/
    }

    final Set<String> touchedAccounts = new ArraySet<>(mAccountsGroup.getPreferenceCount());

    final AccountManager am = AccountManager.get(getContext());
    final AuthenticatorDescription[] authTypes = am.getAuthenticatorTypes();
    final ArrayList<String> allowableAccountTypes = new ArrayList<>(authTypes.length);
    final Context themedContext = getPreferenceManager().getContext();

    for (AuthenticatorDescription authDesc : authTypes) {
        final Context targetContext;
        try {
            targetContext = getContext().createPackageContext(authDesc.packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "Authenticator description with bad package name", e);
            continue;
        } catch (SecurityException e) {
            Log.e(TAG, "Security exception loading package resources", e);
            continue;
        }

        // Main title text comes from the authenticator description (e.g. "Google").
        String authTitle = null;
        try {
            authTitle = targetContext.getString(authDesc.labelId);
            if (TextUtils.isEmpty(authTitle)) {
                authTitle = null; // Handled later when we add the row.
            }
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Authenticator description with bad label id", e);
        }

        // There exist some authenticators which aren't intended to be user-facing.
        // If the authenticator doesn't have a title or an icon, don't present it to
        // the user as an option.
        if (authTitle != null || authDesc.iconId != 0) {
            allowableAccountTypes.add(authDesc.type);
        }

        Account[] accounts = am.getAccountsByType(authDesc.type);
        if (accounts == null || accounts.length == 0) {
            continue; // No point in continuing; there aren't any accounts to show.
        }

        // Icon URI to be displayed for each account is based on the type of authenticator.
        Drawable authImage = null;
        try {
            authImage = targetContext.getDrawable(authDesc.iconId);
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Authenticator has bad resources", e);
        }

        // Display an entry for each installed account we have.
        for (final Account account : accounts) {
            final String key = "account_pref:" + account.type + ":" + account.name;
            Preference preference = findPreference(key);
            if (preference == null) {
                preference = new Preference(themedContext);
            }
            preference.setTitle(authTitle != null ? authTitle : account.name);
            preference.setIcon(authImage);
            preference.setSummary(authTitle != null ? account.name : null);
            preference.setFragment(AccountSyncFragment.class.getName());
            AccountSyncFragment.prepareArgs(preference.getExtras(), account);

            touchedAccounts.add(key);
            preference.setKey(key);

            mAccountsGroup.addPreference(preference);
        }
    }

    for (int i = 0; i < mAccountsGroup.getPreferenceCount();) {
        final Preference preference = mAccountsGroup.getPreference(i);
        final String key = preference.getKey();
        if (touchedAccounts.contains(key) || TextUtils.equals(KEY_ADD_ACCOUNT, key)) {
            i++;
        } else {
            mAccountsGroup.removePreference(preference);
        }
    }

    // Never allow restricted profile to add accounts.
    final Preference addAccountPref = findPreference(KEY_ADD_ACCOUNT);
    if (addAccountPref != null) {
        addAccountPref.setOrder(Integer.MAX_VALUE);
        if (isRestricted()) {
            addAccountPref.setVisible(false);
        } else {
            Intent i = new Intent().setComponent(new ComponentName("com.android.tv.settings",
                    "com.android.tv.settings.accounts.AddAccountWithTypeActivity"));
            i.putExtra(AddAccountWithTypeActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
                    allowableAccountTypes.toArray(new String[allowableAccountTypes.size()]));

            // If there are available account types, show the "add account" button.
            addAccountPref.setVisible(!allowableAccountTypes.isEmpty());
            addAccountPref.setIntent(i);
        }
    }
}

From source file:com.android.launcher2.Launcher.java

private boolean skipCustomClingIfNoAccounts() {
    Cling cling = (Cling) findViewById(R.id.workspace_cling);
    boolean customCling = cling.getDrawIdentifier().equals("workspace_custom");
    if (customCling) {
        AccountManager am = AccountManager.get(this);
        Account[] accounts = am.getAccountsByType("com.google");
        return accounts.length == 0;
    }/* www  . j a  v a 2 s.c o  m*/
    return false;
}

From source file:com.android.soma.Launcher.java

private boolean skipCustomClingIfNoAccounts() {
    Cling cling = (Cling) findViewById(R.id.workspace_cling);
    boolean customCling = cling.getDrawIdentifier().equals("workspace_custom");
    if (customCling) {
        AccountManager am = AccountManager.get(this);
        if (am == null)
            return false;
        Account[] accounts = am.getAccountsByType("com.google");
        return accounts.length == 0;
    }/*from   w w w.ja  v a 2  s. co m*/
    return false;
}

From source file:org.telegram.messenger.MessagesController.java

public void deleteAllAppAccounts() {
    try {/*  w  ww . ja  v a 2s  .  c o  m*/
        AccountManager am = AccountManager.get(ApplicationLoader.applicationContext);
        Account[] accounts = am.getAccountsByType("org.telegram.messenger.account");
        for (Account c : accounts) {
            am.removeAccount(c, null, null);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.tehtotalpwnage.musicphp_android.NavigationActivity.java

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    // Handle navigation view item clicks here.

    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Everything after this point is actually my code.
        StringRequest req = new StringRequest(Request.Method.GET, UrlGenerator.getServerUrl(this) + "/api/user",
                new Response.Listener<String>() {
                    @Override//  ww  w .j a  v a2  s.  c  o  m
                    public void onResponse(String response) {
                        TextView view = new TextView(getApplicationContext());
                        view.setText(response);
                        FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame);
                        layout.removeAllViews();
                        layout.addView(view);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.v(TAG, "Connection error");
                        TextView view = new TextView(getApplicationContext());
                        view.setText(getResources().getString(R.string.error_connection));
                        FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame);
                        layout.removeAllViews();
                        layout.addView(view);
                        NetworkResponse networkResponse = error.networkResponse;
                        if (networkResponse != null
                                && networkResponse.statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                            Log.v(TAG, "Request was unauthorized, meaning that a new token is needed");
                            AccountManager manager = AccountManager.get(getApplicationContext());
                            manager.invalidateAuthToken(MusicPhpAccount.ACCOUNT_TYPE,
                                    getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN));
                            Intent intent = new Intent(NavigationActivity.this, MainActivity.class);
                            startActivity(intent);
                        }
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Accept", "application/json");
                params.put("Authorization",
                        "Bearer " + getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN));
                return params;
            }
        };
        VolleySingleton.getInstance(this).addToRequestQueue(req);
    } else if (id == R.id.nav_gallery) {
        final Context context = this;
        getListing(Item.albums, 0, new VolleyCallback() {
            @Override
            public void onSuccess(JSONArray result) {
                Log.d(TAG, "Volley callback reached");
                String albums[][] = new String[result.length()][3];
                for (int i = 0; i < result.length(); i++) {
                    try {
                        JSONObject object = result.getJSONObject(i);
                        albums[i][0] = object.getString("name");
                        albums[i][1] = object.getJSONObject("artist").getString("name");
                        albums[i][2] = object.getString("id");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                AlbumListingAdapter adapter = new AlbumListingAdapter(context, albums,
                        getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN));
                GridView view = new GridView(context);
                view.setLayoutParams(new DrawerLayout.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT));
                view.setNumColumns(GridView.AUTO_FIT);
                view.setColumnWidth((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 148,
                        getResources().getDisplayMetrics()));
                view.setStretchMode(GridView.STRETCH_SPACING_UNIFORM);
                view.setAdapter(adapter);
                view.setVerticalSpacing((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8,
                        getResources().getDisplayMetrics()));
                FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame);
                layout.removeAllViews();
                layout.addView(view);
                Log.d(TAG, "Adapter setup complete");
            }
        });
    } else if (id == R.id.nav_slideshow) {
        getListing(Item.artists, 0, new VolleyCallback() {
            @Override
            public void onSuccess(JSONArray result) {

            }
        });
    } else if (id == R.id.nav_manage) {
        getListing(Item.tracks, 0, new VolleyCallback() {
            @Override
            public void onSuccess(JSONArray result) {
            }
        });
    } else if (id == R.id.nav_share) {
        Log.d(TAG, "Queue contains " + queue.size() + " items. Displaying queue...");
        ListView view = new ListView(this);
        view.setLayoutParams(new DrawerLayout.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        String tracks[][] = new String[queue.size()][2];
        for (int i = 0; i < queue.size(); i++) {
            MediaSessionCompat.QueueItem queueItem = queue.get(i);
            tracks[i][0] = queueItem.getDescription().getMediaId();
            tracks[i][1] = (String) queueItem.getDescription().getTitle();
        }
        AlbumAdapter adapter = new AlbumAdapter(this, tracks,
                getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN), this);
        view.setAdapter(adapter);
        view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //                    String sAddress = getApplicationContext().getSharedPreferences("Prefs", 0).getString("server", null);
                //                    Bundle bundle = new Bundle();
                //                    bundle.putString("Authorization", "Bearer " + token);
                //                    bundle.putString("Title", tracks[position][1]);
                //                    bundle.putString("art", getIntent().getStringExtra("art"));
                //                    bundle.putString("ID", tracks[position][0]);
                //                    MediaControllerCompat.getMediaController(AlbumActivity.this).getTransportControls().playFromUri(Uri.parse(sAddress + "/api/tracks/" + tracks[position][0] + "/audio"), bundle);
            }
        });
        FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame);
        layout.removeAllViews();
        layout.addView(view);
    } else if (id == R.id.nav_send) {
        String sAddress = getSharedPreferences("Prefs", 0).getString("server", null);
        StringRequest request = new StringRequest(Request.Method.POST, sAddress + "/api/logout",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject object = new JSONObject(response);
                            if (object.getString("status").equals("OK")) {
                                Log.v(TAG, "Logged out successfully. Now redirecting to MainActivity...");
                                AccountManager manager = AccountManager.get(getApplicationContext());
                                Account accounts[] = manager.getAccountsByType(MusicPhpAccount.ACCOUNT_TYPE);
                                int account = 0;
                                for (int i = 0; i < accounts.length; i++) {
                                    if (accounts[i].name.equals(
                                            getIntent().getStringExtra(AccountManager.KEY_ACCOUNT_NAME))) {
                                        account = i;
                                        break;
                                    }
                                }

                                final AccountManagerFuture future;

                                if (Build.VERSION.SDK_INT >= 22) {
                                    future = manager.removeAccount(accounts[account], NavigationActivity.this,
                                            new AccountManagerCallback<Bundle>() {
                                                @Override
                                                public void run(AccountManagerFuture<Bundle> future) {

                                                }
                                            }, null);
                                } else {
                                    future = manager.removeAccount(accounts[account],
                                            new AccountManagerCallback<Boolean>() {
                                                @Override
                                                public void run(AccountManagerFuture<Boolean> future) {

                                                }
                                            }, null);
                                }

                                AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
                                    @Override
                                    protected Void doInBackground(Void... params) {
                                        try {
                                            future.getResult();
                                            Intent intent = new Intent(NavigationActivity.this,
                                                    MainActivity.class);
                                            startActivity(intent);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        return null;
                                    }
                                };
                                task.execute();
                            } else {
                                Log.v(TAG, "Issue with logging out...");
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, "Issue with parsing JSON...");
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Error on logging out...");
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() {
                Map<String, String> params = new HashMap<>();
                params.put("Accept", "application/json");
                params.put("Authorization",
                        "Bearer " + getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN));
                return params;
            }
        };
        VolleySingleton.getInstance(this).addToRequestQueue(request);
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);

    return true;
}