Google Drive API迁移到REST API [英] Google Drive API migration to REST API

查看:102
本文介绍了Google Drive API迁移到REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Since Google is deprecating the Android API, I am trying to migrate to REST API.

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

My app uses Google Drive to save User's data.

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

The User have two options for backup (manual and schedule).

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

The User select an account and it is stored in the app (The email).

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

When needed, the app uses the account to connect to Google Drive and save/delete data.

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

To select which account to use the app is using the AccountPicker.

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

Once an account is selected, the app uses only the account in order to connect to Google Drive (See code below).

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

I would like to keep the current mechanism (The user select an account and when needed the app uses that account to connect to Google Drive).

我看着样品计划和迁移文件,但并没有弄清楚如何做到这一点.

I looked at the sample program and migration documentation, but did not figure out how to do it.

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

It seems that in the sample app, the prompt for an account with a dedicated activity and uses the returned data to sign in to Google Drive (not the behavior I need).

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

I did some code changes, but nothing worked (I got error Drive connection failed (12500) 12500: 12500: Error setting Google account.). See below the modified code.

退出代码

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

推荐答案

首先,您需要登录用户:

First you need to sign in the user:

    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中:

In the 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登录帐户:

Ones the user was signed in you can retrieve the last Google Sign In Account with:

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

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

And to get your DriveServiceHelper you can use the account you have retrieved:

mDriveServiceHelper = getDriveServiceHelper(account);

"getDriveServiceHelper"方法如下:

The "getDriveServiceHelper" method looks like this:

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

这篇关于Google Drive API迁移到REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆