Java Google驱动器SDK验证错误

Java Google驱动器SDK验证错误,java,android,google-drive-api,google-play-services,Java,Android,Google Drive Api,Google Play Services,我正在尝试实现Stephen Wylie的Google Drive示例()。这是我的密码: package com.googledrive.googledriveapp; // For Google Drive / Play Services // Version 1.1 - Added new comments & removed dead code // Stephen Wylie - 10/20/2012 import java.io.IOException; import jav

我正在尝试实现Stephen Wylie的Google Drive示例()。这是我的密码:

package com.googledrive.googledriveapp;
// For Google Drive / Play Services
// Version 1.1 - Added new comments & removed dead code
// Stephen Wylie - 10/20/2012
import java.io.IOException;
import java.util.ArrayList;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.AccountPicker;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.android2.AndroidHttp;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Apps.List;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.DriveRequest;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;

public class MainActivity extends Activity {
    private static final int CHOOSE_ACCOUNT=0;
    private static String accountName;
    private static int REQUEST_TOKEN=0;
    private Button btn_drive;
    private Context ctx = this;
    private Activity a = this;

    public void onCreate(Bundle savedInstanceState) {

        /*
         * Etc... (Other application logic belonging in onCreate)
         */
            btn_drive.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                chooseAccount();
            }
            });
    }

    public void chooseAccount() {
        Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);
        startActivityForResult(intent, CHOOSE_ACCOUNT);
    }

    // Fetch the access token asynchronously.
    void getAndUseAuthTokenInAsyncTask(Account account) {
        AsyncTask<Account, String, String> task = new AsyncTask<Account, String, String>() {
            ProgressDialog progressDlg;
            AsyncTask<Account, String, String> me = this;

            @Override
            protected void onPreExecute() {
                progressDlg = new ProgressDialog(ctx, ProgressDialog.STYLE_SPINNER);
                progressDlg.setMax(100);
                progressDlg.setTitle("Validating...");
                progressDlg.setMessage("Verifying the login data you entered...\n\nThis action will time out after 10 seconds.");
                progressDlg.setCancelable(false);
                progressDlg.setIndeterminate(false);
                progressDlg.setOnCancelListener(new android.content.DialogInterface.OnCancelListener() {
                    public void onCancel(DialogInterface d) {
                        progressDlg.dismiss();
                        me.cancel(true);
                    }
                });
                progressDlg.show();
            }

            @Override
            protected String doInBackground(Account... params) {
                return getAccessToken(params[0]);
            }

            @Override
            protected void onPostExecute(String s) {
                if (s == null) {
                    // Wait for the extra intent
                } else {
                    accountName = s;
                    getDriveFiles();
                }
                progressDlg.dismiss();
            }
        };
        task.execute(account);
    }

    /**
     * Fetches the token from a particular Google account chosen by the user.  DO NOT RUN THIS DIRECTLY.  It must be run asynchronously inside an AsyncTask.
     * @param activity
     * @param account
     * @return
     */
    private String getAccessToken(Account account) {
        try {
            return GoogleAuthUtil.getToken(ctx, account.name, "oauth2:" + DriveScopes.DRIVE_READONLY);  // IMPORTANT: DriveScopes must be changed depending on what level of access you want
        } catch (UserRecoverableAuthException e) {
            // Start the Approval Screen intent, if not run from an Activity, add the Intent.FLAG_ACTIVITY_NEW_TASK flag.
            a.startActivityForResult(e.getIntent(), REQUEST_TOKEN);
            e.printStackTrace();
            return null;
        } catch (GoogleAuthException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private Drive getDriveService() {
        HttpTransport ht = AndroidHttp.newCompatibleTransport();             // Makes a transport compatible with both Android 2.2- and 2.3+
        JacksonFactory jf = new JacksonFactory();                            // You need a JSON parser to help you out with the API response
        Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accountName);
        HttpRequestFactory rf = ht.createRequestFactory(credential);
        Drive.Builder b = new Drive.Builder(ht, jf, null);
        b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {

            @Override
            public void initialize(JsonHttpRequest request) throws IOException {
                DriveRequest driveRequest = (DriveRequest) request;
                driveRequest.setPrettyPrint(true);
                driveRequest.setOauthToken(accountName);
            }
        });
        return b.build();
    }

    /**
     * Obtains a list of all files on the signed-in user's Google Drive account.
     */
    private void getDriveFiles() {
        Drive service = getDriveService();
        Log.d("SiteTrack", "FUNCTION getDriveFiles()");
        Files.List request;
        try {
            request = service.files().list(); // .setQ("mimeType=\"text/plain\"");
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        do {
            FileList files;
            try {
                Log.d("SiteTrack", request.toString());
                files = request.execute();
            } catch (IOException e) {
                e.printStackTrace();
                Log.d("SiteTrack", "Exception");
                return;
            }
            ArrayList<File> fileList = (ArrayList<File>) files.getItems();
            Log.d("SiteTrack", "Files found: " + files.getItems().size());
            for (File f : fileList) {
                String fileId = f.getId();
                String title = f.getTitle();
                Log.d("SiteTrack", "File " + fileId + ": " + title);
            }
            request.setPageToken(files.getNextPageToken());
        } while (request.getPageToken() != null && request.getPageToken().length() >= 0);
    }

    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        if (requestCode == CHOOSE_ACCOUNT && resultCode == RESULT_OK) {
            accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
            GoogleAccountManager gam = new GoogleAccountManager(this);
            getAndUseAuthTokenInAsyncTask(gam.getAccountByName(accountName));
            Log.d("SiteTrack", "CHOOSE_ACCOUNT");
        } else if (requestCode == REQUEST_TOKEN && resultCode == RESULT_OK) {
            accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
            Log.d("SiteTrack", "REQUEST_TOKEN");
        }
    }   
}
有人能帮忙吗?

(作为本教程的补充,让我在Eclipse中添加这一点,您需要转到Android SDK管理器并下载Google Play服务。然后找到Google-Play-Services.jar文件并将其添加为“外部jar”我和OP进行了离线交谈,他已经这样做了,但我忘了提及。)

代码本身无法工作;您可以将其添加到现有的应用程序中,只需将btn_驱动器添加到UI的某个位置,即可让用户连接到Google驱动器。幸运的是,围绕这段代码构建一个Android应用程序将相当容易,即使仅仅创建一个新项目然后将其添加进来可能会更容易。希望这涵盖了所有需要添加的内容

首先,在onCreate中,将“其他应用程序逻辑”部分替换为:

    super.onCreate(savedInstanceState);
    // set up the GUI layout
    setContentView(R.layout.main);
    // set the variables to access the GUI controls
    btn_drive = (Button) findViewById(R.id.btn_drive);
然后,您需要一个真正基本的XML布局。在res/layout中创建一个名为main.xml的新文件(或上面setContentView中称为R.layout的任何文件):


最后,您的清单中可能需要以下权限:

<uses-permission android:name="android.permission.INTERNET" />

祝你好运

(作为本教程的补充,让我在Eclipse中添加这一点,您需要转到Android SDK管理器并下载Google Play服务。然后找到Google-Play-Services.jar文件并将其作为“外部jar”添加到您的Eclipse项目中。我与OP进行了脱机交谈,他已经这样做了,但我忘了提及。)

代码本身无法工作;您可以将其添加到现有的应用程序中,只需将btn_驱动器添加到UI的某个位置,即可让用户连接到Google驱动器。幸运的是,围绕这段代码构建一个Android应用程序将相当容易,即使仅仅创建一个新项目然后将其添加进来可能会更容易。希望这涵盖了所有需要添加的内容

首先,在onCreate中,将“其他应用程序逻辑”部分替换为:

    super.onCreate(savedInstanceState);
    // set up the GUI layout
    setContentView(R.layout.main);
    // set the variables to access the GUI controls
    btn_drive = (Button) findViewById(R.id.btn_drive);
然后,您需要一个真正基本的XML布局。在res/layout中创建一个名为main.xml的新文件(或上面setContentView中称为R.layout的任何文件):


最后,您的清单中可能需要以下权限:

<uses-permission android:name="android.permission.INTERNET" />


祝你好运

当我点击goole_drive按钮时,我发现了这个错误..java.lang.RuntimeException:无法继续活动{com.example.android.notepad/com.example.android.notepad.Preferences}:android.content.ActivityNotFoundException:找不到处理意图的活动{act=com.google.android.gms.common.account.CHOOSE_account(有附加项)}当我点击goole_drive按钮时,我发现了这个错误..java.lang.RuntimeException:无法继续活动{com.example.android.notepad/com.example.android.notepad.Preferences}:android.content.ActivityNotFoundException:找不到处理意图的活动{act=com.google.android.gms.common.account.CHOOSE_account(有附加项)}
<uses-permission android:name="android.permission.INTERNET" />