简体   繁体   English

Android:如何使我的应用记住Google云端硬盘授权?

[英]Android: how to make my app remember Google Drive Authorization?

I got this code from the Internet and I modified it to upload a specific file automatically to Google Drive when starting the activity. 我从互联网上获取了此代码,并对其进行了修改,以便在开始活动时自动将特定文件上传到Google云端硬盘。 It is always ask me to select my Google account when I start this activity! 当我开始这项活动时,总是要求我选择我的Google帐户! I want it ask about Google account once only when started for the first time after install it, How to do that? 我希望它仅在安装后首次启动时询问一次Google帐户,该怎么办?

package com.example.googledrive;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.util.Arrays;
import java.io.IOException;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;
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.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;

public class MainActivity extends Activity {
    static final int                REQUEST_ACCOUNT_PICKER = 1;
    static final int                REQUEST_AUTHORIZATION = 2;
    static final int                REQUEST_DOWNLOAD_FILE = 3;
    static final int                RESULT_STORE_FILE = 4;
    private static Uri              mFileUri;
    private static Drive            mService;
    private GoogleAccountCredential mCredential;
    private Context                 mContext;

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

        // setup for credentials for connecting to the Google Drive account
        mCredential = GoogleAccountCredential.usingOAuth2(this, Arrays.asList(DriveScopes.DRIVE));

        // start activity that prompts the user for their google drive account
        startActivityForResult(mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);        
       // mContext = getApplicationContext(); 
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.main, menu);       
        return true;
    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data)
    {
        switch (requestCode) {
            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);
                        mService = getDriveService(mCredential);
                    }
                    saveFileToDrive();
                }
                break;
            case REQUEST_AUTHORIZATION:
                if (resultCode == Activity.RESULT_OK) {
                    //account already picked
                } else {
                    startActivityForResult(mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
                }
                break;
        }
    }

    private Drive getDriveService(GoogleAccountCredential credential)
    {
        return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
            .build();
    }


    private void saveFileToDrive()
    {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // Create URI from real path
                    String path;
                    path = "/sdcard/DCIM/Camera/a.png";
                    mFileUri = Uri.fromFile(new java.io.File(path));

                    ContentResolver cR = MainActivity.this.getContentResolver();

                    // File's binary content
                    java.io.File fileContent = new java.io.File(mFileUri.getPath());
                    FileContent mediaContent = new FileContent(cR.getType(mFileUri), fileContent);

                    showToast("Selected " + mFileUri.getPath() + "to upload");

                    // File's meta data. 
                    File body = new File();
                    body.setTitle(fileContent.getName());
                    body.setMimeType(cR.getType(mFileUri));

                    com.google.api.services.drive.Drive.Files f1 = mService.files();
                    com.google.api.services.drive.Drive.Files.Insert i1 = f1.insert(body, mediaContent);
                    File file = i1.execute();

                    if (file != null) 
                    {
                        showToast("Uploaded: " + file.getTitle());
                    }
                } catch (UserRecoverableAuthIOException e) {
                    startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
                } catch (IOException e) {
                    e.printStackTrace();
                    showToast("Transfer ERROR: " + e.toString());
                }
            }
        });
        t.start();
    }

    public void showToast(final String toast)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
            }
        });
    }

}

It's been a while, so you probably managed to do this by now, but I was just looking for the same thing and it's fairly easy. 已经有一段时间了,所以您现在可能已经做到了,但是我只是在寻找相同的东西,这很容易。 In the code you use and how it's used on several sites you get an Intent after calling a static method on GoogleAccountCredential. 在您使用的代码以及在多个站点上的使用方式中,您会在GoogleAccountCredential上调用静态方法后得到一个Intent。

You can also create your own, by calling a static method on AccountPicker and define a params that it's only required to pick once. 您还可以通过在AccountPicker上调用静态方法并定义仅需选择一次的参数来创建自己的参数。

Intent accountPicker = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);
startActivityForResult(accountPicker, GOOGLE_ACCOUNT_PICKED);  

The fourth param is what you want and you can read more about it here: https://developers.google.com/android/reference/com/google/android/gms/common/AccountPicker?hl=en 第四个参数是您想要的,您可以在这里阅读有关它的更多信息: https : //developers.google.com/android/reference/com/google/android/gms/common/AccountPicker?hl=zh-CN

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在我的 Android 应用中显示上传到 Google Drive 的进度? - How to show uploading to Google Drive progress in my android App? 在我的Android应用中管理Google云端硬盘上的文件 - Managing files on Google Drive in my Android app 如何仅使用Google Android应用中的Google Drive API在Google云端硬盘上创建和编辑电子表格文件? - How do I create & edit a spreadsheet file on google drive using Google Drive APIs only from my Android app? 如何将图像从我的Android应用程序上传到Google驱动器上的特定文件夹 - how to upload an image from my android app to a specific folder on google drive 我的Android应用中的Google云端硬盘返回错误400 - Google Drive Returning Error 400 in my Android app Google Drive Android API如何将音频文件上传到我的驱动器? 如何同步驱动器文件? - Google Drive Android API how to upload a audio file to my drive ? How to sync drive files? 无法从我的Android应用com.google.android.gms.auth.GoogleAuthException上传到Google驱动器:未知 - cannot upload to google drive from my android app com.google.android.gms.auth.GoogleAuthException: Unknown 如何以编程方式在Google驱动器中的Google驱动器的App文件夹中创建文件夹 - How to Create a Folder in App Folder in google drive in Android Programmatically 如何将视频格式文件从 Android 应用推送到 Google Drive? - How to push a video format file to the Google Drive from an Android app? 如何解决与 api 集成到 android 应用程序相关的错误? - How to resolve the error related to google drive api integration to android app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM