在浏览了很多页面(大部分是矛盾的)之后,我无法编写一个简单的 Android 应用程序,它可以通过 OAuth2 连接到 Google:
我从这个页面开始:
https://developers.google.com/google-apps/tasks/oauth-and-tasks-on-android#account
我确实下载了当前的库,并且不得不体验许多已弃用或缺失的功能:
- GoogleAccountManager 已弃用
- 在当前库中找不到 HttpTransport、AndroidHttp、AccessProtectedResource、GoogleAccessProtectedResource、JacksonFactory
- 通过开发者控制台生成 CLIENT_ID 有效
- 秘密的生成不适用于移动应用,但需要
最新的描述是什么?最新的演示是什么?
以防万一 - 这是我到目前为止所做的。processTokenReceived 中的所有方法都不是库的一部分:
public class ActivityMain extends Activity implements DialogInterface.OnClickListener {
private static final String AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/drive";
private static final String CLIENT_ID = "xxxxxxxxxxxx.apps.googleusercontent.com";
private AccountManager accountManager;
private Account[] accounts;
private String authName;
private String authToken;
@Override
public void onClick(final DialogInterface dialogInterface, final int item) {
processAccountSelected(accounts[item]);
}
@Override
public void onCreate(final Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activitymain);
accountManager = AccountManager.get(this);
accounts = accountManager.getAccountsByType("com.google");
if (accounts == null || accounts.length == 0) {
// TODO
} else if (accounts.length == 1) {
processAccountSelected(accounts[0]);
} else if (accounts.length > 1) {
showDialog(MyConstants.DIALOG_ACCOUNTCHOSER);
}
}
@Override
protected Dialog onCreateDialog(final int id) {
switch (id) {
case MyConstants.DIALOG_ACCOUNTCHOSER:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
String[] names = new String[accounts.length];
for (int i = 0; i < accounts.length; i++) {
names[i] = accounts[i].name;
}
alertDialogBuilder.setItems(names, this);
alertDialogBuilder.setTitle("Select a Google account");
return alertDialogBuilder.create();
}
return null;
}
private void processAccountSelected(final Account account) {
if (account != null) {
authName = account.name.toString();
if (!Tools.isEmpty(authName)) {
Toast.makeText(this, authName, Toast.LENGTH_LONG).show();
accountManager.getAuthToken(account, AUTH_TOKEN_TYPE, null, this,
new AccountManagerCallback<Bundle>() {
public void run(final AccountManagerFuture<Bundle> future) {
try {
authToken = future.getResult().getString(
AccountManager.KEY_AUTHTOKEN);
processTokenReceived();
} catch (OperationCanceledException exception) {
// TODO
} catch (Exception exception) {
Log.d(this.getClass().getName(), exception.getMessage());
}
}
}, null);
}
}
}
private void processTokenReceived() {
if (!Tools.isEmpty(authToken)) {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
AccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
accessToken);
Tasks service = new Tasks(transport, accessProtectedResource, new JacksonFactory());
service.accessKey = CLIENT_ID;
service.setApplicationName("Google-DriveSample/1.0");
}
}
}