这是我解决它的方法。不知道这是否是推荐的方法,但它有效......
在我的条目活动(主要)的 OnCreate 中,我放了......
AccountManager accountManager = AccountManager.get(this);
Account[] accounts = accountManager.getAccountsByType("com.google");
AccountManagerFuture<Bundle> futur;
futur = accountManager.getAuthToken(accounts[0],AUTH_TOKEN_TYPE_USERINFO_PROFILE, null, null,
new OnTokenAcquired(), new Handler(new OnError()));
在我创建的同一个活动中......
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
@Override
public void run(AccountManagerFuture<Bundle> result) {
// Get the result of the operation from the AccountManagerFuture.
Bundle bundle;
try {
bundle = result.getResult();
// The token is a named value in the bundle. The name of the
// value
// is stored in the constant AccountManager.KEY_AUTHTOKEN.
String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
//If token isn't null then let them in and also make sure Crunchy accounts are created
if(token!=null){
ProcessToken pt = new ProcessToken(token);
pt.execute("");
}
Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 0);
return;
}
}catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我还创建了一个 asyncTask 来处理令牌(因为我做了更多的逻辑来设置帐户和设置 cookie)。看起来像这样(我的大部分处理/cookie 逻辑还没有完成)
package com.craig.activities.login;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.AsyncTask;
import android.util.Log;
public class ProcessToken extends AsyncTask<String,Integer,Long>{
private static final String AUTH_ACCESS_TOKEN_URL = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=";
private static final String DEBUG_TAG = "OnTokenAcquired.class";
private static String token="";
public ProcessToken(String tokenValue){
token=tokenValue;
}
@Override
protected Long doInBackground(String... params) {
try {
URL url = new URL(AUTH_ACCESS_TOKEN_URL+token);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
int serverCode= con.getResponseCode();
if(serverCode==200){
Log.i(DEBUG_TAG, "code 200!!!");
//PUT MY LOGIC IN HERE....
}
else{
Log.i(DEBUG_TAG, "Oops, We had an error on authentication");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
不确定这是否是最好的,但它似乎对我有用....