Example usage for android.accounts AccountManager removeAccount

List of usage examples for android.accounts AccountManager removeAccount

Introduction

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

Prototype

public AccountManagerFuture<Bundle> removeAccount(final Account account, final Activity activity,
        AccountManagerCallback<Bundle> callback, Handler handler) 

Source Link

Document

Removes an account from the AccountManager.

Usage

From source file:org.voidsink.anewjkuapp.utils.AppUtils.java

public static void removeAccout(AccountManager accountManager, Account account) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        accountManager.removeAccount(account, null, null, null);
    } else {/*  w  w w. j  a  v a 2s .  c o  m*/
        accountManager.removeAccount(account, null, null);
    }
    Log.d(TAG, "account removed");
}

From source file:com.murrayc.galaxyzoo.app.LoginUtils.java

/** Don't call this from the main UI thread.
 *
 * @param context// w  ww .j ava2 s . c  o  m
 */
public static void removeAccount(final Context context, final String accountName) {
    final AccountManager accountManager = AccountManager.get(context);
    final Account account = new Account(accountName, LoginUtils.ACCOUNT_TYPE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        //Trying to call this on an older Android version results in a
        //NoSuchMethodError exception.
        //There is no AppCompat version of the AccountManager API to
        //avoid the need for this version check at runtime.
        accountManager.removeAccount(account, null, null, null);
    } else {
        //noinspection deprecation
        //Note that this needs the MANAGE_ACCOUNT permission on
        //SDK <=22.
        //noinspection deprecation
        accountManager.removeAccount(account, null, null);
    }
}

From source file:org.andstatus.app.account.AccountSettingsFragment.java

private void onRemoveAccount() {
    StateOfAccountChangeProcess state = ((AccountSettingsActivity) getActivity()).getState();
    if (state.builder.isPersistent()) {
        for (android.accounts.Account account : PersistentAccounts.getAccounts(getActivity())) {
            if (state.getAccount().getAccountName().equals(account.name)) {
                MyLog.i(this, "Removing account: " + account.name);
                android.accounts.AccountManager am = AccountManager.get(getActivity());
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
                    am.removeAccount(account, getActivity(), null, null);
                } else {
                    am.removeAccount(account, null, null);
                }/*from  ww  w . java 2s. c om*/
            }
        }
        getActivity().finish();
    }
}

From source file:at.bitfire.davdroid.ui.AccountActivity.java

private void deleteAccount() {
    AccountManager accountManager = AccountManager.get(this);

    if (Build.VERSION.SDK_INT >= 22)
        accountManager.removeAccount(account, this, new AccountManagerCallback<Bundle>() {
            @Override/*  www.j a va 2s .  c  om*/
            public void run(AccountManagerFuture<Bundle> future) {
                try {
                    if (future.getResult().getBoolean(AccountManager.KEY_BOOLEAN_RESULT))
                        finish();
                } catch (OperationCanceledException | IOException | AuthenticatorException e) {
                    App.log.log(Level.SEVERE, "Couldn't remove account", e);
                }
            }
        }, null);
    else
        accountManager.removeAccount(account, new AccountManagerCallback<Boolean>() {
            @Override
            public void run(AccountManagerFuture<Boolean> future) {
                try {
                    if (future.getResult())
                        finish();
                } catch (OperationCanceledException | IOException | AuthenticatorException e) {
                    App.log.log(Level.SEVERE, "Couldn't remove account", e);
                }
            }
        }, null);
}

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/*from   w w w  .  j a v a  2s.co 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;
}