Example usage for android.accounts AccountManager KEY_AUTHTOKEN

List of usage examples for android.accounts AccountManager KEY_AUTHTOKEN

Introduction

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

Prototype

String KEY_AUTHTOKEN

To view the source code for android.accounts AccountManager KEY_AUTHTOKEN.

Click Source Link

Document

Bundle key used for the auth token value in results from #getAuthToken and friends.

Usage

From source file:eu.trentorise.smartcampus.communicator.HomeActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    mTutorialHelper.onTutorialActivityResult(requestCode, resultCode, data);
    if (requestCode == SCAccessProvider.SC_AUTH_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            String token = data.getExtras().getString(AccountManager.KEY_AUTHTOKEN);
            if (token == null) {
                CommunicatorHelper.endAppFailure(this, R.string.app_failure_security);
            } else {
                initData(false);//ww w  . j  av a2  s.c  om
            }
        } else if (resultCode == RESULT_CANCELED
                && requestCode == SCAccessProvider.SC_AUTH_ACTIVITY_REQUEST_CODE) {
            CommunicatorHelper.endAppFailure(this, R.string.token_required);
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

From source file:org.mozilla.gecko.sync.syncadapter.SyncAdapter.java

private void invalidateAuthToken(Account account) {
    AccountManagerFuture<Bundle> future = getAuthToken(account, null, null);
    String token;//from www .j  av  a2s .c  om
    try {
        token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
        mAccountManager.invalidateAuthToken(Constants.ACCOUNTTYPE_SYNC, token);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Couldn't invalidate auth token: " + e);
    }
}

From source file:sk.mpage.androidsample.drawerwithauthenticator.MainActivity.java

private void getTokenForAccountCreateIfNeeded(String accountType, String authTokenType) {
    final AccountManagerFuture<Bundle> future = mAccountManager.getAuthTokenByFeatures(accountType,
            authTokenType, null, this, null, null, new AccountManagerCallback<Bundle>() {
                @Override//from w ww  .j  a v  a  2s  .  c o m
                public void run(AccountManagerFuture<Bundle> future) {
                    Bundle bnd = null;
                    try {
                        bnd = future.getResult();
                        authToken = bnd.getString(AccountManager.KEY_AUTHTOKEN);
                        if (authToken != null) {
                            String accountName = bnd.getString(AccountManager.KEY_ACCOUNT_NAME);
                            mConnectedAccount = new Account(accountName, AccountGeneral.ACCOUNT_TYPE);
                            //callback after connected
                            setAppUIForUser();
                        } else {
                            getTokenForAccountCreateIfNeeded(AccountGeneral.ACCOUNT_TYPE,
                                    AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, null);
}

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

/**
 * Get auth token for existing account (assumes pre-existing account)
 *//*from  w w w  .j  av  a2 s .c  om*/
public void getToken(final AuthCallback callback) {
    Log.d(TAG, "getToken > getting session token");
    //sessionComplete = false;
    //TODO: match userID to account with the same userID store in AccountManager
    Account account = getAccount();

    if (account == null) {
        Log.v(TAG, "getToken > getAccount > account is null");
        return;
    }

    am.getAuthToken(account, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS, null, mActivity,
            new AccountManagerCallback<Bundle>() {
                @Override
                public void run(AccountManagerFuture<Bundle> future) {
                    try {
                        Bundle bundle = future.getResult();
                        String authtoken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                        Log.v(TAG, "> getToken, token received: " + authtoken);
                        callback.onSuccess(authtoken);
                    } catch (OperationCanceledException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (AuthenticatorException e) {
                        e.printStackTrace();
                    }
                }
            }, 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 www .ja va 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:cl.chileagil.agileday2012.fragment.MainFragment.java

private void chooseAccount() {
    accountManager.getAccountManager().getAuthTokenByFeatures(GoogleAccountManager.ACCOUNT_TYPE,
            AUTH_TOKEN_TYPE, null, MainFragment.this, null, null, new AccountManagerCallback<Bundle>() {

                public void run(AccountManagerFuture<Bundle> future) {
                    Bundle bundle;//w  w w. ja  v a2 s  .co m
                    try {
                        bundle = future.getResult();
                        setAccountName(bundle.getString(AccountManager.KEY_ACCOUNT_NAME));
                        setAuthToken(bundle.getString(AccountManager.KEY_AUTHTOKEN));
                        onAuthToken();
                    } catch (OperationCanceledException e) {
                        // user canceled
                    } catch (AuthenticatorException e) {
                        Log.e(TAG, e.getMessage(), e);
                    } catch (IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            }, null);
}

From source file:org.pixmob.feedme.ui.EntriesFragment.java

private void authenticateAccount(String accountName) {
    Log.i(TAG, "Authenticating account: " + accountName);

    final Activity a = getActivity();
    final AccountManager am = (AccountManager) a.getSystemService(Context.ACCOUNT_SERVICE);
    final Account account = new Account(accountName, GOOGLE_ACCOUNT);
    am.getAuthToken(account, "reader", null, a, new AccountManagerCallback<Bundle>() {
        @Override/*ww  w.ja v  a 2 s  . c o  m*/
        public void run(AccountManagerFuture<Bundle> resultContainer) {
            String authToken = null;
            final Bundle result;
            try {
                result = resultContainer.getResult();
                authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
            } catch (IOException e) {
                Log.w(TAG, "I/O error while authenticating account " + account.name, e);
            } catch (OperationCanceledException e) {
                Log.w(TAG, "Authentication was canceled for account " + account.name, e);
            } catch (AuthenticatorException e) {
                Log.w(TAG, "Authentication failed for account " + account.name, e);
            }

            if (authToken == null) {
                Toast.makeText(a, a.getString(R.string.authentication_failed), Toast.LENGTH_SHORT).show();
            } else {
                Log.i(TAG, "Authentication done");
                onAuthenticationDone(account.name, authToken);
            }
        }
    }, null);
}

From source file:com.mobiperf.speedometer.AccountSelector.java

private void getAuthToken(AccountManagerFuture<Bundle> result) {
    Logger.i("getAuthToken() called, result " + result);
    String errMsg = "Failed to get login cookie. ";
    Bundle bundle;/*from   w w w  . ja  v  a 2s  . com*/
    try {
        bundle = result.getResult();
        Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT);
        if (intent != null) {
            // User input required. (A UI will pop up for user's consent to
            // allow
            // this app access account information.)
            Logger.i("Starting account manager activity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else {
            Logger.i("Executing getCookie task");
            synchronized (this) {
                this.authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                this.checkinFuture = checkinExecutor.submit(new GetCookieTask());
            }
        }
    } catch (OperationCanceledException e) {
        Logger.e(errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    } catch (AuthenticatorException e) {
        Logger.e(errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    } catch (IOException e) {
        Logger.e(errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    }
}

From source file:be.evias.cloudLogin.cloudLoginRunPointActivity.java

/**
 * Get the auth token for an existing account on the AccountManager.
 *
 * @param account       Account// ww w  . j a v a 2  s .  co m
 * @param authTokenType String
 */
private void getAccountAuthToken(final Account account, String authTokenType) {
    final AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(account, authTokenType, null, this,
            null, null);

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Bundle bnd = future.getResult();

                final String authtoken = bnd.getString(AccountManager.KEY_AUTHTOKEN);
                Log.d("cloudLogin",
                        "cloudLoginRunPointActivity/getAccountAuthToken: User still logged in. Bundle: " + bnd);

                SharedPreferences.Editor editor = mPrefs.edit();
                editor.putBoolean("cloudlogin_active_account", true);
                editor.putString("cloudlogin_active_account_name", account.name);
                editor.commit();

                displayNavigationDrawer(bnd, account);
            } catch (Exception e) {
                e.printStackTrace();
                showMessage(e.getMessage(), Toast.LENGTH_LONG);

                SharedPreferences.Editor editor = mPrefs.edit();
                editor.putBoolean("cloudlogin_active_account", false);
                editor.commit();
            }
        }
    }).start();
}

From source file:com.mobiperf.AccountSelector.java

private void getAuthToken(AccountManagerFuture<Bundle> result) {
    Logger.i("getAuthToken() called, result " + result);
    String errMsg = "Failed to get login cookie. ";
    Bundle bundle;//from  w  ww.  j ava 2s .  c  om
    try {
        bundle = result.getResult();
        Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT);
        if (intent != null) {
            // User input required. (A UI will pop up for user's consent to allow
            // this app access account information.)
            Logger.i("Starting account manager activity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else {
            Logger.i("Executing getCookie task");
            synchronized (this) {
                this.authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                this.checkinFuture = checkinExecutor.submit(new GetCookieTask());
            }
        }
    } catch (OperationCanceledException e) {
        Logger.e(errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    } catch (AuthenticatorException e) {
        Logger.e(errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    } catch (IOException e) {
        Logger.e(errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    }
}