我有一个android应用程序,需要用户的许可才能访问其谷歌电子表格(范围为谷歌电子表格API(。
当应用程序第一次启动时,一切都很好,我可以很好地访问电子表格我正在将用户选择的电子邮件地址保存到共享首选项中
我想要的是,在用户下次启动应用程序时(第一次之后(,应用程序将只获得令牌(因为我已经有了用户的电子邮件地址(,而用户不必再次通过帐户选择器。
我想这以前已经做过了,因为用户只应该选择一次他的帐户。尽管如此,我还是想不出什么是最好的做法。
他是Google OAuth 2.0级
直接从这里http://developer.android.com/google/auth/http-auth.html
public class GoogleAccountActivity extends Activity {
static final int REQUEST_CODE_PICK_ACCOUNT = 1000;
static final int REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR = 1001;
static final int REQUEST_CODE_RECOVER_FROM_AUTH_ERROR = 1002;
String mEmail;
private static final String SCOPE =
"oauth2:https://spreadsheets.google.com/feeds/";
private Intent homeIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
homeIntent=new Intent(this, HomeActivity.class);
// next activity tto launch
pickUserAccount();
}
private void getUsername() {
if (mEmail == null) {
pickUserAccount();
} else {
if (isDeviceOnline()) {
new GetUsernameTask(this, mEmail, SCOPE).execute();
} else {
Toast.makeText(this, R.string.not_online, Toast.LENGTH_LONG).show();
}
}
}
public boolean isDeviceOnline() {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
} else {
return false;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
// Receiving a result from the AccountPicker
if (resultCode == RESULT_OK) {
mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
// With the account name acquired, go get the auth token
getUsername();
} else if (resultCode == RESULT_CANCELED) {
// The account picker dialog closed without selecting an account.
// Notify users that they must pick an account to proceed.
Toast.makeText(this, R.string.pick_account, Toast.LENGTH_SHORT).show();
}
} else if ((requestCode == REQUEST_CODE_RECOVER_FROM_AUTH_ERROR ||
requestCode == REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)
&& resultCode == RESULT_OK) {
// Receiving a result that follows a GoogleAuthException, try auth again
getUsername();
}
}
private void pickUserAccount() {
String[] accountTypes = new String[]{"com.google"};
Intent intent = AccountPicker.newChooseAccountIntent(null, null,
accountTypes, false, null, null, null, null);
startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
}
public void handleException(final Exception e) {
// Because this call comes from the AsyncTask, we must ensure that the following
// code instead executes on the UI thread.
runOnUiThread(new Runnable() {
@Override
public void run() {
if (e instanceof GooglePlayServicesAvailabilityException) {
// The Google Play services APK is old, disabled, or not present.
// Show a dialog created by Google Play services that allows
// the user to update the APK
int statusCode = ((GooglePlayServicesAvailabilityException)e)
.getConnectionStatusCode();
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(statusCode,
GoogleAccountActivity.this,
REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
dialog.show();
} else if (e instanceof UserRecoverableAuthException) {
// Unable to authenticate, such as when the user has not yet granted
// the app access to the account, but the user can fix this.
// Forward the user to an activity in Google Play services.
Intent intent = ((UserRecoverableAuthException)e).getIntent();
startActivityForResult(intent,
REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
}
}
});
}
public class GetUsernameTask extends AsyncTask<Void, Void, String>{
Activity mActivity;
String mScope;
String mEmail;
GetUsernameTask(Activity activity, String name, String scope) {
this.mActivity = activity;
this.mScope = scope;
this.mEmail = name;
}
/**
* Executes the asynchronous job. This runs when you call execute()
* on the AsyncTask instance.
*/
@Override
protected String doInBackground(Void... params) {
try {
String token = fetchToken();
if (token != null) {
homeIntent.putExtra("userToken", token);
startActivity(homeIntent); // starting the Home Activity
}
} catch (IOException e) {
// The fetchToken() method handles Google-specific exceptions,
// so this indicates something went wrong at a higher level.
// TIP: Check for network connectivity before starting the AsyncTask.
}
return null;
}
/**
* Gets an authentication token from Google and handles any
* GoogleAuthException that may occur.
*/
protected String fetchToken() throws IOException {
try {
return GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
} catch (UserRecoverableAuthException userRecoverableException) {
// GooglePlayServices.apk is either old, disabled, or not present
// so we need to show the user some UI in the activity to recover.
handleException(userRecoverableException);
} catch (GoogleAuthException fatalException) {
// Some other type of unrecoverable exception has occurred.
// Report and log the error as appropriate for your app.
}
return null;
}
}
}
它在第一次发布时运行良好,但我不确定下次该怎么办。
总结:
我想知道我每次启动应用程序时是否需要获得代币??
如果是这样的话,我如何只提取代币(和处理异常(,而不进行第一次启动所需的账户挑选和其他工作。
我需要使用刷新令牌吗?因为我读过它,但在do.中没有看到任何例子
任何帮助都将不胜感激。
谢谢,Ofek
如果是android手机或任何具有google+的设备,您只需检查google+登录即可。
如果你正在使用任何其他没有gmail的设备或安卓设备,第一次你需要从谷歌获取代币。稍后您需要刷新您的令牌,因为它可能会过期。
参考编号:https://developers.google.com/accounts/docs/OAuth2ForDevices