Code example for AccountManager

Methods: getAuthToken, invalidateAuthToken

0
    initialize(); 
    addGoogleAuthHeader(request, authToken);
    HttpResponse response = client.execute(request);
    if (response.getStatusLine().getStatusCode() == 401) {
      Log.i(LOG_TAG, "Invalid token: " + authToken);
      accountManager.invalidateAuthToken(ACCOUNT_TYPE, authToken);
      authToken = getAuthToken();
      removeGoogleAuthHeaders(request);
      addGoogleAuthHeader(request, authToken);
      Log.i(LOG_TAG, "new token: " + authToken);
      response = client.execute(request);
    } 
    return response;
  } 
 
 
  /** 
   * Forget about the account the user chose. 
   * The AccountChooser remembers (in shared prefs) the 
   * chosen account.  Call this if you want to change the account 
   * this service is associated with. 
   */ 
  @Override 
  public void forgetAccountName() { 
    accountChooser.forgetAccountName();
  } 
 
  private static void addGoogleAuthHeader(HttpUriRequest request, String token) {
    if (token != null) {
      Log.i(LOG_TAG, "adding auth token token: " + token);
      request.addHeader("Authorization", AUTHORIZATION_HEADER_PREFIX  + token);
    } 
  } 
 
  private static void removeGoogleAuthHeaders(HttpUriRequest request) {
    for (Header header : request.getAllHeaders()) {
      if (header.getName().equalsIgnoreCase("Authorization") &&
              header.getValue().startsWith(AUTHORIZATION_HEADER_PREFIX)) {
        Log.i(LOG_TAG, "Removing header:" + header);
        request.removeHeader(header);
      } 
    } 
  } 
 
  /** 
   * Uses Google Account Manager to retrieve auth token that can 
   * be used to access various Google APIs -- e.g., the Google Voice api. 
   */ 
  public String getAuthToken() throws ClientProtocolException {
    Account account = accountChooser.findAccount();
    if (account != null) {
      AccountManagerFuture<Bundle> future;
      future = accountManager.getAuthToken(account, service, null, activity, null, null);
      Log.i(LOG_TAG, "Have account, auth token: " + future);
      Bundle result;
      try { 
        result = future.getResult();
        return result.getString(AccountManager.KEY_AUTHTOKEN);