如何在 Android 应用程序中设置 Google Drive Credentials? [英] How setup Google Drive Credentials within Android App?

查看:16
本文介绍了如何在 Android 应用程序中设置 Google Drive Credentials?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该应用已在Google API 控制台"中注册为已安装的应用"- 似乎这是 Android 应用的正确设置,不是吗?

The app was registered in the "Google API console" as an "installed application" - seems that this is the right setting for an Android app, no?

所以我确实有一个 Client-Id 而没有 Secret-Id.明确地说:它不是网络应用程序,也不是 Google Drive-App - 它是一个 Android 应用程序,用于访问 Google Drive 云中的其他用户数据.

So I do have a Client-Id and no Secret-Id. To make it clear: It's no Web-app and no Google Drive-App - it's an Android App accessing other users data in the Google Drive cloud.

在应用程序中,我获取帐户(有效)并请求令牌(有效).现在我想使用该令牌和客户端 ID 连接到 Google Drive.结果是401,无效凭据".这段代码有什么问题?

Within the app I fetch the account (works) and I do request a token (works). Now I want to connect to Google Drive with that token and the Client-Id. The result is a "401, invalid credential". What's wrong with this code?

public class ActivityMain extends Activity implements DialogInterface.OnClickListener {

    // https://developers.google.com/drive/scopes
    private static final String AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/drive";

    // https://code.google.com/apis/console/
    private static final String CLIENT_ID = "999999999999999.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 processListFiles(final Drive drive) {
        List<File> result = new ArrayList<File>();
        Files.List request = null;
        try {
            request = drive.files().list();
        } catch (IOException exception) {
        }

        do {
            try {
                FileList files = request.execute();

                result.addAll(files.getItems());
                request.setPageToken(files.getNextPageToken());
            } catch (IOException exception) {
                // --> 401 invalid credentials
            }
        } while (request.getPageToken() != null && request.getPageToken().length() > 0);
    }

    private void processTokenReceived() {
        if (!Tools.isEmpty(authToken)) {
            final HttpTransport transport = AndroidHttp.newCompatibleTransport();
            final JsonFactory jsonFactory = new GsonFactory();
            GoogleCredential credential = new GoogleCredential();
            credential.setAccessToken(authToken);
            Drive drive = new Drive.Builder(transport, jsonFactory, credential)
                    .setApplicationName(getString(R.string.txt_appname))
                    .setJsonHttpRequestInitializer(new GoogleKeyInitializer(CLIENT_ID))
                    .build();

            if (drive != null) {
                processListFiles(drive);
            }
        }
    }
}

我不得不说这是一团糟.网络上有很多页面只显示部分,还有很多页面使用不推荐、丢失或不同的方法来做同样的事情.在我看来,没有两个页面显示从 Android 应用中的 Google Drive 获取数据的相同方式.

I have to say that this is a full load of mess. There are so many pages in the web showing parts only and there are so many pages using deprecated, missing or different methods to do the same. There are, in my opinion, not two pages showing the same way to get data from Google Drive from within an Android app.

非常感谢任何帮助.

我可以自己解决.这是不同变化的组合:

I could solve it myself. It was a combination of different changes:

  • 必须将 android:minSdkVersion="11" 设置为要求
  • 必须使用当前的库:google-api-client-1.11.0-beta.jar、google-api-client-android-1.11.0-beta.jar、google-api-services-drive-v2-rev9-1.8.0-beta.jar、google-http-client-1.11.0-beta.jar、google-http-client-android-1.11.0-beta.jar、google-http-client-gson-1.11.0-beta.jar、google-http-client-jackson2-1.11.0-beta.jar、google-oauth-client-1.11.0-beta.jar、gson-2.1.jar、guava-11.0.1.jar、jackson-core-2.0.5.jar、jsr305-1.3.9.jar

这是当前获取驱动对象的部分:

This is the current part to get the Drive Object:

    GoogleCredential credential = new GoogleCredential();
    credential.setAccessToken(authToken);

    HttpTransport transport = AndroidHttp.newCompatibleTransport();

    JsonFactory jsonFactory = new AndroidJsonFactory();

    drive = new Drive.Builder(transport, jsonFactory, credential)
            .setApplicationName(getString(R.string.txt_appname))
            .setJsonHttpRequestInitializer(
                    new GoogleKeyInitializer(APIKEY_SIMPLE))
            .build();
    if (drive != null) {
    }

推荐答案

是的,文档很难理解.

只要改变

new GoogleKeyInitializer(CLIENT_ID)

new GoogleKeyInitializer(SIMPLE_API_ACCESS_KEY)

它应该可以工作.

您可以在 Google 的 API 控制台下找到您的 SIMPLE_API_ACCESS_KEYAPI 访问页面的简单 API 访问部分(API 密钥).如果此部分不可用,您必须先在服务页面上激活 Drive API 访问权限.

You can find your SIMPLE_API_ACCESS_KEY in Google's APIs Console under the Simple API Access section of the API Access page (the API key). If this section is not available, you have to first activate Drive API access on the Services page.

这篇关于如何在 Android 应用程序中设置 Google Drive Credentials?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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