如何使用Android API将本地文件从外部目录上传到Google驱动器?

时间:2018-11-23 21:00:56

标签: java android drive

我在Google云端硬盘API方面取得了一些进展,可以创建文件和文件夹。但是,我似乎无法弄清楚如何将文件夹从设备存储上传到Google Drive,或者如何在Drive Folders中创建文件夹或文件。 我也想知道如何在任何给定的驱动器文件夹中检索文件。 我将不胜感激,提供了带有示例的详细说明,而不提供指向官方文档的链接,因为我已经为之奋斗了好几天(而且我知道我不是唯一的一个)。

这是到目前为止我得到的代码。

public abstract class DriveActivity extends UtilsActivity {

    private static final int REQUEST_CODE_SIGN_IN = 77;
    public static final String PIONEER_DRIVE_ROOT_FOLDER = "Pioneer Backups ID_77";
    public FileManagerHelper mFileManagerHelper;
    private GoogleSignInClient mGoogleSignInClient;
    private DriveClient mDriveClient;
    public OptionsClass mOptionsClass;


    /**
     * Inits file manager and Google Sign In Client
     */
    protected void Init() {

        mFileManagerHelper = new FileManagerHelper(this);
        mOptionsClass = new OptionsClass(getApplicationContext());

        mGoogleSignInClient = buildSignInOptions();


        if (loggedIntoGoogleDrive() && mOptionsClass.getEnableDrive()) {

            /*
            Create the main pioneer folder, where all the backups will be stored. 
             */
            //TODO heck if the folder already exists
//            createFolder(getRootFolderTask(),
//                    new MetadataChangeSet.Builder()
//                            .setTitle(PIONEER_DRIVE_ROOT_FOLDER)
//                            .setDescription("Root Folder For All Pioneer Backups")
//                            .build(), false);

        }

    }

    /**
     * Sign user out of google account
     */
    public void signOutOfGoogleDrive() {
        onProcessStart(PROCESS_KEY_ACCOUNT_RELATED);
        mGoogleSignInClient
                .signOut()
                /*
                Success
                 */
                .addOnSuccessListener(aVoid -> {
                    onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
                    Toast.makeText(DriveActivity.this, "Signed Out", Toast.LENGTH_SHORT).show();
                })
                /*
                Failure
                 */
                .addOnFailureListener(e -> {
                    onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
                    e.printStackTrace();
                    Toast.makeText(DriveActivity.this, "Failure " + e.getMessage(), Toast.LENGTH_SHORT).show();
                })
                /*
                Completion
                 */
                .addOnCompleteListener(task -> {
                    onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
                    Toast.makeText(DriveActivity.this, "Done", Toast.LENGTH_SHORT).show();
                });
    }

    /**
     * Get user data, to enable Google Drive
     *
     * @return ResourceClient
     */
    public DriveResourceClient getDriveResourceClient() {
        return Drive.getDriveResourceClient(getApplicationContext(), getGoogleAccount());
    }

    public boolean loggedIntoGoogleDrive() {
        return getGoogleAccount() != null;
    }

    /**
     * @return the las logged in account
     */
    public GoogleSignInAccount getGoogleAccount() {
        return GoogleSignIn.getLastSignedInAccount(this);
    }

    /**
     * @return the scopes the user needs to grant to the app
     */
    private Set<Scope> getRequiredScopes() {
        Set<Scope> requiredScopes = new HashSet<>(2);
        requiredScopes.add(Drive.SCOPE_FILE);
        requiredScopes.add(Drive.SCOPE_APPFOLDER);
        return requiredScopes;
    }

    /**
     * Start sign in activity.
     */
    public void signInToGoogleDrive() {
        onProcessStart(PROCESS_KEY_ACCOUNT_RELATED);
        /*
        Check if we have all the required scopes and if the user if logged in
         */
        if (loggedIntoGoogleDrive() && getGoogleAccount().getGrantedScopes().containsAll(getRequiredScopes())) {

            initializeDriveClient(getGoogleAccount());

            onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);

        } else {

            GoogleSignInOptions signInOptions =
                    new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                            .requestScopes(Drive.SCOPE_FILE)
                            .requestScopes(Drive.SCOPE_APPFOLDER)
                            .build();

            GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
            startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
        }

        startActivityForResult(mGoogleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);


    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == REQUEST_CODE_SIGN_IN) {
            onProcessEnd(PROCESS_KEY_ACCOUNT_RELATED);
        }

    }

    public void initializeDriveClient(GoogleSignInAccount signInAccount) {
        mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);

        mDriveClient.getUploadPreferences().addOnSuccessListener(transferPreferences -> {

        });
    }

    /**
     * Build a Google SignIn client.
     */
    private GoogleSignInClient buildSignInOptions() {
        GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestScopes(Drive.SCOPE_FILE)
                .requestScopes(Drive.SCOPE_APPFOLDER)
                .build();
        return GoogleSignIn.getClient(this, signInOptions);
    }

    /**
     * Uploads a file to drive
     *
     * @param file to upload
     */
    public void uploadFileToDrive(File file, String des) {

        if (!loggedIntoGoogleDrive()) {
            signInToGoogleDrive();
            return;
        } else if (!mOptionsClass.getEnableDrive()) {
            makeText("Enable Drive Backup First");
        }


//      getRootFolderTask()
//                .continueWithTask(task -> {
//
//                    DriveFolder parentFolder = task.getResult();
//
//                    String fileName = file.getName();
//
//                    String from = file.getAbsolutePath();
//
//                    String fileDes =
//                            "Pioneer Backup File. Uploaded: " + CalendarHelper.getSimpleFormattedDateAndTime(true);
//
//                    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
//                            .setTitle(fileName)
//                            .setMimeType("text/plain")
//                            .setDescription(fileDes + "_" + from)
//                            .setStarred(true)
//                            .build();
//
//                    return getDriveResourceClient().createFile(parentFolder, changeSet, null);
//                })
//                .addOnSuccessListener(this,
//                        driveFile -> {
//                            Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
//                        })
//                .addOnFailureListener(this, e -> {
//                    Toast.makeText(this, "Error " + e.getMessage(), Toast.LENGTH_SHORT).show();
//                });
    }

    private Task<DriveFolder> getRootFolderTask() {
        return getDriveResourceClient().getRootFolder();
    }

    /**
     * Creates a file inside a folder
     */
    private void createFile(@NonNull Task<DriveFolder> folderToGoIn, String name) {

        addTaskListenerToDriveFolder(folderToGoIn.continueWithTask(task -> {
            if (task.getResult() != null) {
                DriveFolder parentFolder = task.getResult();
                MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                        .setTitle(name)
                        .setMimeType("text/plain")
                        .setStarred(true)
                        .build();
                return getDriveResourceClient().createFolder(parentFolder, changeSet);
            } else {
                makeText("Error");
                return null;
            }

        }), false);
    }

    private void createFolder(@NonNull Task<DriveFolder> folderToGoIn, MetadataChangeSet folderMetadata, boolean notify) {
        addTaskListenerToDriveFolder(folderToGoIn
                .continueWithTask(task -> {
                    if (task.getResult() != null) {
                        DriveFolder parentFolder = task.getResult();
                        return getDriveResourceClient().createFolder(parentFolder, folderMetadata);
                    } else {
                        makeText("Error");
                        return null;
                    }
                }), notify);
    }

    private Task<DriveContents> readFile(DriveFile file) {
        return getDriveResourceClient().openFile(file, DriveFile.MODE_READ_ONLY);
    }


    private Task<MetadataBuffer> getFoldersIn(DriveFolder driveFolder) {

        Query query = new Query.Builder()
                .addFilter(Filters.eq(SearchableField.MIME_TYPE, DriveFolder.MIME_TYPE))
                .build();


        return getDriveResourceClient().queryChildren(driveFolder, query);

    }

    public List<File> getDriveBackups() {
        //TODO get actual files inside the backup folder
        return getLocalBackups();
    }


    public void viewDriveBackups() {
        /*
        Open the Google Drive app to view the backups folder
         */
    }

    /**
     * Adds task failure, success, complete and cancelled listeners.
     * Automatically notifies the user of state
     *
     * @param task to add listeners
     */
    private void addTaskListenerToDriveFolder(Task<DriveFolder> task, boolean notify) {
        onProcessStart(PROCESS_KEY_BACKUP_RELATED);
        task
                .addOnCanceledListener(() -> {
                    onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
                    if (notify)
                        makeText("Cancelled");

                })
                .addOnCompleteListener(task1 -> {
                    onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
                    if (notify)
                        makeText("Completed");
                })
                .addOnSuccessListener(driveFolder -> {
                    onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
                    if (notify)
                        makeText("Success");
                })
                .addOnFailureListener(this, e -> {
                    onProcessEnd(PROCESS_KEY_BACKUP_RELATED);
                    if (notify)
                        makeText("Error " + e.getMessage());
                });
    }


}

0 个答案:

没有答案