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

时间:2015-06-23 08:49:02

标签: android google-drive-api

我需要在我的应用上访问一个共享文件夹,这是在google驱动器“drive.google.com”上创建的共享文件夹。这将包括我的应用程序上的所有子文件和文件夹。我试图使用谷歌驱动器api来访问数据,但它没有显示我在驱动器上的任何数据。  我使用了this链接来访问该文件夹。

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

1 个答案:

答案 0 :(得分:1)

虽然没有明确记录,但可以将Android应用程序连接到公共云端硬盘文件夹。

先决条件

  1. 在适用于您应用的开发者控制台中设置项目
  2. 使用Keytool实用程序生成签名证书指纹
  3. 使用您的应用程序包名称和步骤2中生成的指纹添加API密钥标识符(Android)。
  4. 创建服务帐户。
  5. 将您在上一步下载的JSon文件添加到项目的raw文件夹中。由于Android资源名称策略,您可能需要重命名它。
  6. 获取您要访问的共享文件夹的ID(不确定您是否需要它)。
  7. 前三个步骤描述为here。第四步描述there。您可能需要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();
                }
            }
        }
    
    }