Google Drive API迁移到REST API

时间:2018-12-15 19:52:01

标签: android google-drive-api

由于Google不推荐使用Android API,因此我正尝试迁移到REST API。

我的应用程序使用Google云端硬盘保存用户的数据。

用户有两个备份选项(手动和计划)。

用户选择一个帐户并将其存储在应用程序(电子邮件)中。

在需要时,该应用使用该帐户连接到Google云端硬盘并保存/删除数据。

要选择要使用该应用程序的帐户,请使用AccountPicker。

选择一个帐户后,该应用仅使用该帐户连接到Google云端硬盘(请参见下面的代码)。

我想保留当前机制(用户选择一个帐户,并且在需要时应用程序使用该帐户连接到Google云端硬盘)。

我查看了sample程序和migration文档,但没有弄清楚该怎么做。

似乎在示例应用程序中,提示您输入具有专用活动的帐户,并使用返回的数据登录Google云端硬盘(不是我需要的行为)。

我做了一些代码更改,但没有任何效果(我收到错误驱动器连接失败(12500)12500:12500:设置Google帐户时出错。)。参见下面的修改后的代码。

退出代码

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) {
    }
}

1 个答案:

答案 0 :(得分:0)

首先,您需要登录用户:

    GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestScopes(new Scope(DriveScopes.DRIVE_FILE))
            .build();
    GoogleSignInClient client = GoogleSignIn.getClient(activity, signInOptions);

    // The result of the sign-in Intent is handled in onActivityResult
    startActivityForResult(client.getSignInIntent(), RC_CODE_SIGN_IN);

在onActivityResult中:

GoogleSignIn.getSignedInAccountFromIntent(result)
                .addOnSuccessListener(new OnSuccessListener<GoogleSignInAccount>() {
                    @Override
                    public void onSuccess(GoogleSignInAccount googleSignInAccount) {
                        HyperLog.i(TAG, "Signed in as " + googleSignInAccount.getEmail());
                        mDriveServiceHelper = getDriveServiceHelper(googleSignInAccount);
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        HyperLog.e(TAG, "Unable to sign in!", e);
                    }
                });

用户已登录,您可以使用以下方式检索上一个Google登录帐户:

GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(getActivity());

要获取DriveServiceHelper,您可以使用已获取的帐户:

mDriveServiceHelper = getDriveServiceHelper(account);

“ getDriveServiceHelper”方法如下:

private DriveServiceHelper getDriveServiceHelper(GoogleSignInAccount googleSignInAccount) {
        // Use the authenticated account ot sign in to the Drive service
        GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
                activity, Collections.singleton(DriveScopes.DRIVE_FILE));
        credential.setSelectedAccount(googleSignInAccount.getAccount());

        Drive googleDriveService = new Drive.Builder(AndroidHttp.newCompatibleTransport(),
                new GsonFactory(), credential)
                .setApplicationName("COL Reminder")
                .build();
        return new DriveServiceHelper(googleDriveService);
    }