繁体   English   中英

在我的应用程序中访问Google云端硬盘数据

[英]Access Google drive data in my app

我需要访问我的应用程序上的一个共享文件夹,这是在Google驱动器“ drive.google.com”上创建的共享文件夹。 这将包括我应用程序中的所有子文件和文件夹。 我尝试使用Google Drive API访问数据,但未显示驱动器上的任何数据。 我已使用链接访问该文件夹。

请帮我解决这个问题。 请提供有效的参考链接给我。

尽管没有明确记录,但可以将Android应用程序连接到公共Drive文件夹。

先决条件

  1. 在开发人员控制台中为您的应用设置项目
  2. 使用Keytool实用程序生成签名证书指纹
  3. 使用您的应用程序包名称和在步骤2中生成的指纹添加API密钥标识符(Android)。
  4. 创建一个服务帐户。
  5. 将您在上一步下载的JSon文件添加到项目的原始文件夹中。 由于Android资源名称政策,您可能需要重命名。
  6. 获取您要访问的共享文件夹的ID(虽然不确定您将需要它)。

此处描述前三个步骤。 那里描述了第四步。 您可能需要Drive REST API文档。

然后是代码...

我做了一个片段。 我只是在这里保留了基本的东西。 我正在请求公用文件夹的文件列表。

import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.json.jackson2.JacksonFactory;
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.List;


public class FragmentDownload extends Fragment {

    GoogleCredential aCredential;
    ProgressDialog mProgress;

    /**
     * Required empty public constructor
     */
    public FragmentDownload() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_download, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);    

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

        // Initialize credentials object.
        try {
            aCredential = GoogleCredential
                    .fromStream(getContext().getResources().openRawResource(R.raw.json_file))
                    .createScoped(DriveScopes.all());
        } catch (Exception e) {
            e.printStackTrace();
        }

        getResultsFromApi();
    }

    /**
     * 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) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    /**
     * Attempt to call the API, after verifying that all the preconditions are
     * satisfied. The preconditions are: Google Play Services installed, an
     * account was selected and the device currently has online access. If any
     * of the preconditions are not satisfied, the app will prompt the user as
     * appropriate.
     */
    private void getResultsFromApi() {
        if (! isDeviceOnline()) {
            Toast.makeText(getContext(), "No network connection available.", Toast.LENGTH_LONG).show();
        } else {
            new MakeRequestTask(aCredential).execute();
        }
    }

    /**
     * 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(GoogleCredential credential) {
            HttpTransport transport = AndroidHttp.newCompatibleTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            mService = new com.google.api.services.drive.Drive.Builder(
                    transport, jsonFactory, credential)
                    .setApplicationName("appName")
                    .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<>();
            FileList result = mService.files().list()
                    .setCorpus("user")
                    .setQ("'public_gdrive_folder_id' in parents")
                    .setOrderBy("name")
                    .setSpaces("drive")
                    .setFields("files(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() {
            mProgress.show();
        }

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

        @Override
        protected void onCancelled() {
            mProgress.hide();
            if (mLastError != null) {
                Toast.makeText(getContext(), "The following error occurred:\n"
                        + mLastError.getMessage(), Toast.LENGTH_LONG).show();

               // }
            } else {
                Toast.makeText(getContext(), "Request cancelled.", Toast.LENGTH_LONG).show();
            }
        }
    }

}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM