简体   繁体   中英

Access Google drive data in my app

I need to access one shared folder on my app, this is a shared folder created on google drive "drive.google.com". This would include all its child file(s) and folders on my app. I tried to use Google drive api's to access the data but it was not showing any data that i have on drive. I have used this link to access the folder.

Please help me with a solution to this. Please provide me the effective reference link.

Tough it is not clearly documented, it is possible to connect an Android app to a public Drive folder.

Prerequisites

  1. Set up a project in Developers Console for your app
  2. Generate the signing certificate fingerprint with the Keytool utility
  3. Add an API Key identifier (Android) using your application package name and the fingerprint generated in step 2.
  4. Create a Service Account.
  5. Add the JSon file you downloaded at the previous step to the raw folder of your project. You may need to rename it because of the Android resource name policy.
  6. Get the id of the shared folder you want to access (not sure you will need it though).

The first three steps are described here . The fourth step is described there . And you will probably need the Drive REST API documentation.

Then the code...

I did it in a Fragment. I just kept the essential things here. I am requesting the file list of a public folder.

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();
            }
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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