【发布时间】:2018-12-15 19:52:01
【问题描述】:
由于 Google 正在弃用 Android API,我正在尝试迁移到 REST API。
我的应用使用 Google Drive 来保存用户的数据。
用户有两个备份选项(手动和计划)。
用户选择一个帐户并将其存储在应用程序(电子邮件)中。
在需要时,应用会使用该帐户连接到 Google Drive 并保存/删除数据。
使用 AccountPicker 选择要使用该应用的帐户。
选择帐户后,该应用将仅使用该帐户连接到 Google 云端硬盘(请参阅下面的代码)。
我想保留当前机制(用户选择一个帐户,应用程序在需要时使用该帐户连接到 Google Drive)。
我查看了sample 程序和migration 文档,但不知道该怎么做。
似乎在示例应用程序中,提示具有专用活动的帐户并使用返回的数据登录 Google 云端硬盘(不是我需要的行为)。
我做了一些代码更改,但没有任何效果(我收到错误 Drive connection failed (12500) 12500: 12500: Error setting Google account.)。见下方修改后的代码。
退出代码
GoogleApiClient.Builder builder = new GoogleApiClient.Builder(context)
.addApi(Drive.API)
.setAccountName(accountName)
.addScope(Drive.SCOPE_FILE)
.addScope(Drive.SCOPE_APPFOLDER);
client = builder.build();
client.registerConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnectionSuspended(int cause) {
}
@Override
public void onConnected(Bundle arg0) {
latch.countDown();
}
});
client.registerConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult result) {
error = new DriveConnectException();
if (result.hasResolution()) {
if (activity != null) {
try {
result.startResolutionForResult(activity, requestCode);
error = new InResolutionException();
} catch (IntentSender.SendIntentException e) {
}
}
}
latch.countDown();
}
});
client.connect();
try {
latch.await();
} catch (Exception ignored) {
}
if (client.isConnected()) {
// do some work
} else {
// report error
}
修改后的代码
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.setAccountName(accountName)
.requestScopes(new Scope(DriveScopes.DRIVE))
.build();
client = GoogleSignIn.getClient(context, signInOptions);
Task<GoogleSignInAccount> task = client.silentSignIn();
if (task.isSuccessful()) {
signInAccount = task.getResult();
} else {
final CountDownLatch latch = new CountDownLatch(1);
task.addOnCompleteListener(new OnCompleteListener<GoogleSignInAccount>() {
@Override
public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
try {
signInAccount = task.getResult(ApiException.class);
} catch (ApiException e) {
// I always ends up here.
}
latch.countDown();
}
});
try {
latch.await();
} catch (Exception ignored) {
}
}
【问题讨论】:
-
您找到解决方案了吗?我也有同样的问题。活动登录有效,但我也需要它来自动“备份上传”。所以我想登录并使用这个客户端在后台上传文件。
-
不,我没有,还在等待。
-
刚找到解决办法,看我的回答。
-
谢谢,我会试试看,如果它也适用于我,请告诉您。