当前位置: 首页 > 知识库问答 >
问题:

使用Google Drive API时的无限“选择帐户”循环

费星晖
2023-03-14

我正在尝试设置一个Android应用程序,该应用程序可以使用Google Drive REST API概述中的指南操作存储在我个人Google Drive帐户上的文件。

我按照示例代码允许用户连接到帐户,但无论是否选择帐户名称或按下取消按钮,“选择帐户”对话框都会不断重新出现。

我认为问题在于,在测试mCredential时,refreshResults()方法总是返回null。getSelectedAccountName()即使从“帐户选择器”对话框中选择了帐户名。然而,我不知道为什么会发生这种情况,也不知道如何修复它。如果有更有经验的人能给我建议,我将不胜感激。谢谢

我的代码如下:

import android.accounts.AccountManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityIOException;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class HomeActivity extends AppCompatActivity{

    GoogleAccountCredential mCredential;
    ProgressDialog mProgress;

    static final int REQUEST_ACCOUNT_PICKER = 1000;
    static final int REQUEST_AUTHORIZATION = 1001;
    static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
    private static final String PREF_ACCOUNT_NAME = "accountName";
    private static final String[] SCOPES = { DriveScopes.DRIVE_METADATA_READONLY };

    public TextView mOutputText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Initialize credentials and service object.
        SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
        mCredential = GoogleAccountCredential.usingOAuth2(
                getApplicationContext(), Arrays.asList(SCOPES))
                .setBackOff(new ExponentialBackOff())
                .setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));

        mProgress = new ProgressDialog(this);
        mProgress.setMessage("Calling Drive API ...");

        setContentView(R.layout.activity_home);
        mOutputText = (TextView) findViewById(R.id.textStatus);

    @Override
    protected void onResume() {
        super.onResume();

            if (isGooglePlayServicesAvailable()) {
                refreshResults();
            } else {
                mOutputText.setText("Google Play Services required: " +
                        "after installing, close and relaunch this app.");
            }
        }

    /**
     * Called when an activity launched here (specifically, AccountPicker
     * and authorization) exits, giving you the requestCode you started it with,
     * the resultCode it returned, and any additional data from it.
     * @param requestCode code indicating which activity result is incoming.
     * @param resultCode code indicating the result of the incoming
     *     activity result.
     * @param data Intent (containing result data) returned by incoming
     *     activity result.
     */
    @Override
    protected void onActivityResult(
            int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch(requestCode) {
            case REQUEST_GOOGLE_PLAY_SERVICES:
                if (resultCode != RESULT_OK) {
                    isGooglePlayServicesAvailable();
                }
                break;
            case REQUEST_ACCOUNT_PICKER:
                if (resultCode == RESULT_OK && data != null &&
                        data.getExtras() != null) {

                    String accountName =
                            data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);

                    if (accountName != null) {
                        mCredential.setSelectedAccountName(accountName);
                        SharedPreferences settings =
                                getPreferences(Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = settings.edit();
                        editor.putString(PREF_ACCOUNT_NAME, accountName);
                        editor.apply();
                    }
                } else if (resultCode == RESULT_CANCELED) {
                    mOutputText.setText("Account unspecified.");
                }
                break;
            case REQUEST_AUTHORIZATION:
                if (resultCode != RESULT_OK) {
                    chooseAccount();
                }
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * Attempt to get a set of data from the Drive API to display. If the
     * email address isn't known yet, then call chooseAccount() method so the
     * user can pick an account.
     */
    private void refreshResults() {
        if (mCredential.getSelectedAccountName() == null) {
            chooseAccount();
        } else {
            if (isDeviceOnline()) {
                new MakeRequestTask(mCredential).execute();
            } else {
                mOutputText.setText("No network connection available.");
            }
        }
    }

    /**
     * Starts an activity in Google Play Services so the user can pick an
     * account.
     */
    private void chooseAccount() {
        startActivityForResult(
                mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
    }

    /**
     * Checks whether the device currently has a network connection.
     * @return true if the device has a network connection, false otherwise.
     */
    private boolean isDeviceOnline() {
        ConnectivityManager connMgr =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    /**
     * Check that Google Play services APK is installed and up to date. Will
     * launch an error dialog for the user to update Google Play Services if
     * possible.
     * @return true if Google Play Services is available and up to
     *     date on this device; false otherwise.
     */
    private boolean isGooglePlayServicesAvailable() {
        final int connectionStatusCode =
                //GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
                GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
        if (GoogleApiAvailability.getInstance().isUserResolvableError(connectionStatusCode)) {
            showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
            return false;
        } else if (connectionStatusCode != ConnectionResult.SUCCESS ) {
            return false;
        }
        return true;
    }

    /**
     * Display an error dialog showing that Google Play Services is missing
     * or out of date.
     * @param connectionStatusCode code describing the presence (or lack of)
     *     Google Play Services on this device.
     */
    void showGooglePlayServicesAvailabilityErrorDialog(
            final int connectionStatusCode) {
        //Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
        Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(
                HomeActivity.this,
                connectionStatusCode,
                REQUEST_GOOGLE_PLAY_SERVICES);
        dialog.show();
    }

    /**
     * An asynchronous task that handles the Drive API call.
     * Placing the API calls in their own task ensures the UI stays responsive.
     */
    private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
        private com.google.api.services.drive.Drive mService = null;
        private Exception mLastError = null;

        public MakeRequestTask(GoogleAccountCredential credential) {
            HttpTransport transport = AndroidHttp.newCompatibleTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            mService = new com.google.api.services.drive.Drive.Builder(
                    transport, jsonFactory, credential)
                    .setApplicationName("Media Vault")
                    .build();
        }

        /**
         * Background task to call Drive API.
         * @param params no parameters needed for this task.
         */
        @Override
        protected List<String> doInBackground(Void... params) {
            try {
                return getDataFromApi();
            } catch (Exception e) {
                mLastError = e;
                cancel(true);
                return null;
            }
        }

        /**
         * Fetch a list of up to 10 file names and IDs.
         * @return List of Strings describing files, or an empty list if no files
         *         found.
         * @throws IOException
         */
        private List<String> getDataFromApi() throws IOException {
            // Get a list of up to 10 files.
            List<String> fileInfo = new ArrayList<String>();
            FileList result = mService.files().list()
                    .setPageSize(10)
                    .setFields("nextPageToken, items(id, name)")
                    .execute();
            List<File> files = result.getFiles();
            if (files != null) {
                for (File file : files) {
                    fileInfo.add(String.format("%s (%s)\n",
                            file.getName(), file.getId()));
                }
            }
            return fileInfo;
        }

        @Override
        protected void onPreExecute() {
            mOutputText.setText("");
            mProgress.show();
        }

        @Override
        protected void onPostExecute(List<String> output) {
            mProgress.hide();
            if (output == null || output.size() == 0) {
                mOutputText.setText("No results returned.");
            } else {
                output.add(0, "Data retrieved using the Drive API:");
                mOutputText.setText(TextUtils.join("\n", output));
            }
        }

        @Override
        protected void onCancelled() {
            mProgress.hide();
            if (mLastError != null) {
                if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
                    showGooglePlayServicesAvailabilityErrorDialog(
                            ((GooglePlayServicesAvailabilityIOException) mLastError)
                                    .getConnectionStatusCode());
                } else if (mLastError instanceof UserRecoverableAuthIOException) {
                    startActivityForResult(
                            ((UserRecoverableAuthIOException) mLastError).getIntent(),
                            HomeActivity.REQUEST_AUTHORIZATION);
                } else {
                    mOutputText.setText("The following error occurred:\n"
                            + mLastError.getMessage());
                }
            } else {
                mOutputText.setText("Request cancelled.");
            }
        }
    }


}

共有3个答案

戚兴思
2023-03-14

您必须使用Google官方的Google Drive Api Quickstart。链接我可以确认,不幸的是,到目前为止,它还不能工作。即使我的设备上只有一个gmail帐户,这也会导致无限的登录循环。也许可以考虑将驱动器Api页面上的代码作为起点。这应该行得通

童铭晨
2023-03-14

我能想到的一件事是,如果没有检索到PREF\u ACCOUNT\u NAME,则setSelectedAccountName的值将默认为null,因此这可能会导致问题。

我所能看到的唯一区别是如何实例化mCredential。尝试检查Android的授权请求(使用GoogleAppClient,而不是GoogleAccountCredential)。

边翔宇
2023-03-14

我遇到了完全相同的问题,在我的情况下,循环是由于我没有为我的应用程序创建凭据......

详情如下:https://developers.google.com/drive/android/get-started

您必须检索调试和生产环境的SHA-1密钥,并将它们添加到Google Developers控制台中的凭据中,如指南中所述。

添加这些凭据后,循环立即停止。

 类似资料:
  • 我正在尝试实现已保存的游戏代码,我可以毫无问题地保存和加载,所有数据都正常。但当我与Google连接时,代码会与默认帐户连接。我尝试使用帐户选择器并使用返回的邮件,但帐户是相同的,相同的数据。我需要选择帐户,否则我的代码无效。 这是我的连接代码: 我需要帮助解决这个问题。我在mainactivity和preferencesactivity中使用此代码,无法选择用于保存进度的帐户。 默认帐户使用ma

  • 我们的应用程序正在使用 gapi.auth.登录进行身份验证。问题是,当用户登录到多个帐户时,不会显示帐户选择下拉列表。目前,为了克服这个问题,应用程序设置。显然,这并不是很有效。 使用时是否可以显示多用户选择下拉列表gapi.auth.signin? 用gapi.auth.authorize代替吗?(相关问题) 非常感谢。

  • 我将angular 8与oidc客户端js一起使用。我已连接到IdentityServer4(代码流PKCE)。在我打开应用程序(在主组件内)后,我想检查用户是否经过身份验证。这就是我调用SignInDirect()的原因。我没有手动单击按钮,而是在构造函数内部调用它(当我单击按钮调用SignInDirect()时,整个流程都起作用)。问题是我被困在无限循环中。Angular一直在调用Idenit

  • 我的应用程序中有以下工作流: 用户登录我的自定义应用程序 用户点击一个按钮链接他们的YouTube帐户 应用程序使用下面的代码列表发出服务器端请求 用户被重定向到google auth url 此时,发生了两件事之一: [我从来不想要这种行为] - 如果用户只登录了一个谷歌帐户(即mail,谷歌域名应用套件等),则永远不会要求用户选择要链接的帐户。它只是假设他们想要使用他们登录的那个,并继续其快乐

  • 问题内容: 此代码将导致无限循环的机会是什么? 实际上,这会导致无限循环。我的怀疑是因为我没有服用,是真的吗? 问题答案: 是。除非您不打电话,否则它将永远不会继续进行下一项。Beause 将返回您已在列表/集中添加的对象。

  • 问题内容: 我一直在使用React 16.7-alpha中的新钩子系统,并且当我正在处理的状态是对象或数组时陷入useEffect的无限循环中。 首先,我使用useState并使用一个空对象启动它,如下所示: 然后,在useEffect中,我再次使用setObj将其设置为空对象。作为第二个参数,我传递了[obj],希望如果对象的 内容 没有更改,它也不会更新。但是它一直在更新。我猜是因为不管内容如