Can someone provide an up-to-date Android guide for Google Drive REST API v3?

前端 未结 3 1077
甜味超标
甜味超标 2020-12-05 20:19

Myself and many others have been struggling with setting up the Google Drive REST API v3 to work with Android apps. This mainly stems from the fact that the official Google

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 20:51

    The article that I referred to while trying to figure out how to use the Drive REST API was on this page

    I'm pretty new to Android, but here's how I get the list of files' IDs. Hope this helps you

    create a method that returns a list of Files (do not mix them up with java.io.Files). They are instances of com.google.api.services.drive.model.File; The method below is a part of DriveServiceHelper class from the deprecation tutorial on github. Check the source files to see how mExecutor and mDriveService instances get created

    public Task queryFiles() {
        return Tasks.call(mExecutor, () ->
                mDriveService.files().list().setSpaces("drive").execute());
    }
    

    then you can iterate the list and get IDs of each file

    for (File file : fileList.getFiles()) {
       file.getId()
    }
    

    Once you get the ID, you can remove or update files here's an example of a method for removing duplicate files your app will create each time you make an upload to google drive:

    private void mQuery(String name) {
        if (mDriveServiceHelper != null) {
            Log.d(TAG, "Querying for files.");
    
            mDriveServiceHelper.queryFiles()
                    .addOnSuccessListener(fileList -> {
                        for (File file : fileList.getFiles()) {
                            if(file.getName().equals(name))
                                mDriveServiceHelper.deleteFolderFile(file.getId()).addOnSuccessListener(v-> Log.d(TAG, "removed file "+file.getName())).
                                        addOnFailureListener(v-> Log.d(TAG, "File was not removed: "+file.getName()));
                        }
                    })
                    .addOnFailureListener(exception -> Log.e(TAG, "Unable to query files.", exception));
        }
    }
    

    and here's the deleteFolderFile method from DriveServiceHelper class

    public Task deleteFolderFile(String fileId) {
        return Tasks.call(mExecutor, () -> {
            // Retrieve the metadata as a File object.
            if (fileId != null) {
                mDriveService.files().delete(fileId).execute();
            }
            return null;
        });
    }
    

    NB! this is not the best approach if you need to perform a query on a large list of files. It's just a draft to help you get an idea. At least mQuery func can be improved by utilizing a binary search algorithm to look up a particular file in a list.

提交回复
热议问题