Example usage for android.accounts AccountManagerCallback AccountManagerCallback

List of usage examples for android.accounts AccountManagerCallback AccountManagerCallback

Introduction

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

Prototype

AccountManagerCallback

Source Link

Usage

From source file:org.creativecommons.thelist.utils.ListUser.java

public void addNewAccount(String accountType, String authTokenType, final AuthCallback callback) {
    final AccountManagerFuture<Bundle> future = am.addAccount(accountType, authTokenType, null, null, mActivity,
            new AccountManagerCallback<Bundle>() {
                @Override/*from w  w w.  j  a  v  a  2 s.c o m*/
                public void run(AccountManagerFuture<Bundle> future) {
                    try {
                        Bundle bnd = future.getResult();
                        //TODO: does this addAccountExplicitly
                        //addSavedItemsToUserList();
                        Log.d(TAG, " > addNewAccount Bundle received: " + bnd);
                        callback.onSuccess(bnd.getString(AccountManager.KEY_AUTHTOKEN));

                    } catch (Exception e) {
                        //Log.d(TAG, e.getMessage());
                        Log.d(TAG, "addNewAccount > Error adding new account");
                    }
                }
            }, null);
}

From source file:org.creativecommons.thelist.utils.ListUser.java

public void removeAccounts(final AuthCallback callback) {
    Account[] availableAccounts = am.getAccountsByType(AccountGeneral.ACCOUNT_TYPE);
    for (Account account : availableAccounts) {
        am.removeAccount(account, new AccountManagerCallback<Boolean>() {
            @Override//from ww  w.  j a  v  a  2s . com
            public void run(AccountManagerFuture<Boolean> future) {
                Log.d(TAG, " > removeAccounts, accounts removed");
                callback.onSuccess("removedAccounts");
            }
        }, 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//  w  w  w  . j a v a 2 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;
}

From source file:com.sefford.beauthentic.activities.LoginActivity.java

void createGoogleAccount(final GoogleSignInAccount acct) {
    final Account account = new Account(acct.getDisplayName(), AuthenticAuthenticator.ACCOUNT_TYPE);
    final AccountManager am = AccountManager.get(this);
    final Bundle data = new Bundle();
    data.putInt(AuthenticAuthenticator.EXTRA_TYPE, AuthenticAuthenticator.Type.GOOGLE.ordinal());
    data.putString(AccountManager.KEY_ACCOUNT_NAME, acct.getDisplayName());
    data.putString(AccountManager.KEY_AUTHTOKEN, acct.getIdToken());
    am.confirmCredentials(account, data, null, new AccountManagerCallback<Bundle>() {
        @Override/*from  w w w . java2 s .c o m*/
        public void run(AccountManagerFuture<Bundle> future) {
            try {
                final Bundle result = future.getResult();
                if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)) {
                    Sessions.addAccount(am, account, "", Bundle.EMPTY);
                    am.setAuthToken(account, AuthenticAuthenticator.AUTHTOKEN_TYPE,
                            result.getString(AccountManager.KEY_AUTHTOKEN));
                    am.setUserData(account, AuthenticAuthenticator.EXTRA_TYPE,
                            Integer.toString(AuthenticAuthenticator.Type.GOOGLE.ordinal()));
                    notifyLoginToGCM(AuthenticAuthenticator.Type.GOOGLE.ordinal(), account.name, "",
                            result.getString(AccountManager.KEY_AUTHTOKEN));
                    googleApi.saveCredential(new Credential.Builder(acct.getEmail())
                            .setAccountType(IdentityProviders.GOOGLE).setName(acct.getDisplayName())
                            .setProfilePictureUri(acct.getPhotoUrl()).build(),
                            new SmartlockCredentialCallback());
                }
            } catch (OperationCanceledException e) {
                Snackbar.make(vLoginForm, R.string.error_operation_cancelled, Snackbar.LENGTH_LONG).show();
            } catch (IOException e) {
                Snackbar.make(vLoginForm, R.string.error_not_connected_to_internet, Snackbar.LENGTH_LONG)
                        .show();
            } catch (AuthenticatorException e) {
                Snackbar.make(vLoginForm, R.string.error_invalid_credentials, Snackbar.LENGTH_LONG).show();
            }
        }
    }, null);
}

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/*from  ww w.jav a2s.co m*/
            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:com.microsoft.windowsazure.mobileservices.MobileServiceClient.java

/**
 * Invokes Microsoft Azure Mobile Service authentication using a the Google
 * account registered in the device//  w ww. j av a 2  s  .  co m
 *
 * @param activity The activity that triggered the authentication
 * @param account  The account used for the login operation
 * @param scopes   The scopes used as authentication token type for login
 */
public ListenableFuture<MobileServiceUser> loginWithGoogleAccount(Activity activity, Account account,
        String scopes) {
    final SettableFuture<MobileServiceUser> future = SettableFuture.create();

    try {
        if (account == null) {
            throw new IllegalArgumentException("account");
        }

        final MobileServiceClient client = this;

        AccountManagerCallback<Bundle> authCallback = new AccountManagerCallback<Bundle>() {

            @Override
            public void run(AccountManagerFuture<Bundle> futureBundle) {
                try {
                    if (futureBundle.isCancelled()) {
                        future.setException(new MobileServiceException("User cancelled"));
                        // callback.onCompleted(null, new
                        // MobileServiceException("User cancelled"), null);
                    } else {
                        Bundle bundle = futureBundle.getResult();

                        String token = (String) (bundle.get(AccountManager.KEY_AUTHTOKEN));

                        JsonObject json = new JsonObject();
                        json.addProperty("access_token", token);

                        ListenableFuture<MobileServiceUser> loginFuture = client
                                .login(MobileServiceAuthenticationProvider.Google, json);

                        Futures.addCallback(loginFuture, new FutureCallback<MobileServiceUser>() {
                            @Override
                            public void onFailure(Throwable e) {
                                future.setException(e);
                            }

                            @Override
                            public void onSuccess(MobileServiceUser user) {
                                future.set(user);
                            }
                        });
                    }
                } catch (Exception e) {
                    future.setException(e);
                }
            }
        };

        AccountManager acMgr = AccountManager.get(activity.getApplicationContext());
        acMgr.getAuthToken(account, scopes, null, activity, authCallback, null);

    } catch (Exception e) {
        future.setException(e);
    }

    return future;
}

From source file:com.nononsenseapps.notepad.MainActivity.java

private void enableSync() {
    final Activity activity = this;
    // Get the first Google account on the device
    final Account[] accounts = AccountManager.get(activity).getAccountsByType("com.google");
    if (accounts.length > 0) {
        final Account account = accounts[0];

        // Request access
        AccountManager.get(activity).getAuthToken(account, SyncAdapter.AUTH_TOKEN_TYPE, null, activity,
                new AccountManagerCallback<Bundle>() {

                    @Override/*  w w  w  .  java 2 s.c  o  m*/
                    public void run(AccountManagerFuture<Bundle> future) {
                        // This is the callback class, it handles all the
                        // steps
                        // after requesting access
                        try {
                            String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
                            if (token != null && !token.equals("") && account != null) {
                                // Get preference editor
                                Editor editor = PreferenceManager.getDefaultSharedPreferences(activity).edit();

                                // Write account name to prefs
                                editor.putString(SyncPrefs.KEY_ACCOUNT, account.name);

                                // Set it syncable
                                ContentResolver.setIsSyncable(account, NotePad.AUTHORITY, 1);

                                // Write to pref
                                editor.putBoolean(SyncPrefs.KEY_SYNC_ENABLE, true);

                                // Commit prefs
                                editor.commit();

                                // Then request sync
                                requestSync(account.name);
                            }
                        } catch (OperationCanceledException e) {
                            Log.e("SyncFix", "Error1");
                            // if the request was canceled for any reason
                        } catch (AuthenticatorException e) {
                            Log.e("SyncFix", "Error2");
                            // if there was an error communicating with the
                            // authenticator or
                            // if the authenticator returned an invalid
                            // response
                        } catch (IOException e) {
                            Log.e("SyncFix", "Error3");
                            // if the authenticator returned an error
                            // response that
                            // indicates that it encountered an IOException
                            // while
                            // communicating with the authentication server
                        }
                    }
                }, null);

    }
}