goole驱动文件上传下载问题在android中

时间:2016-08-15 10:16:47

标签: android download upload

我在Android中实现了一个项目,用户可以从谷歌驱动器备份和恢复文件。

然而,有一些问题,例如它在驱动器api sigining之后最初没有首次上传文件。我也可以看到谷歌驱动器中的更新文件,但下载旧文件时获取。请建议我一个解决方案。

这是我的代码

 if (mGoogleApiClient == null) {
                        // Create the API client and bind it to an instance variable.
                        // We use this instance as the callback for connection and connection
                        // failures.
                        // Since no account name is passed, the user is prompted to choose.
                        mGoogleApiClient = new GoogleApiClient.Builder(Myportfolio.this)
                                 .addApi(Drive.API)
                                .addScope(Drive.SCOPE_FILE)
                                .addConnectionCallbacks(Myportfolio.this)
                                .addOnConnectionFailedListener(Myportfolio.this)
                                .build();
                    }
mGoogleApiClient.connect();

 @Override
public void onConnected(Bundle connectionHint) {

    Log.i(TAG, "API client connected.");
    Drive.DriveApi.requestSync(mGoogleApiClient).setResultCallback(new ResultCallback<com.google.android.gms.common.api.Status>() {
        @Override
        public void onResult(com.google.android.gms.common.api.Status status) {
            if (!status.getStatus().isSuccess()) {
                Log.e("SYNCING", "ERROR" + status.getStatusMessage());
            } else {
                Log.e("SYNCING", "SUCCESS");
                // execute async task to list AppFolderContents

            }
        }
    });
    Query query = new Query.Builder()
            .addFilter(Filters.eq(SearchableField.TITLE, "backup.txt"))
            .build();
    Drive.DriveApi.query(mGoogleApiClient, query)
            .setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {


                @Override
                public void onResult(@NonNull DriveApi.MetadataBufferResult result) {

                    if (result.getMetadataBuffer().getCount() > 0) {
                        resu = String.valueOf(result.getMetadataBuffer().get(0).getDriveId().getResourceId());
                        Log.d("Value of id", resu);
                        // resu = resu.substring(resu.indexOf(":"));
                        if (status == 1) {
                            Drive.DriveApi.fetchDriveId(mGoogleApiClient, resu).setResultCallback(idCallback);
                            Log.d("Google:", "update");
                        } else if (status == 2) {
                            Drive.DriveApi.fetchDriveId(mGoogleApiClient, resu).setResultCallback(idCallback1);
                            Log.d("Google:", "fetch");
                        }
                    }
                    else {
                            Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(driveContentsCallback);
                            Log.d("Google:", "create new");
                        }
                    }
            });



}

final ResultCallback<DriveApi.DriveIdResult> idCallback = new ResultCallback<DriveApi.DriveIdResult>() {
    @Override
    public void onResult(DriveApi.DriveIdResult result) {
        if (!result.getStatus().isSuccess()) {
           Log.d("file status:","Cannot find DriveId. Are you authorized to view this file?");
            return;
        }
        DriveId driveId = result.getDriveId();
        DriveFile file = driveId.asDriveFile();
        new EditContentsAsyncTask().execute(file);

    }
};
final private ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback = new
        ResultCallback<DriveApi.DriveContentsResult>() {
            @Override
            public void onResult(DriveApi.DriveContentsResult result) {
                if (!result.getStatus().isSuccess()) {
                    //showMessage("Error while trying to create new file contents");

                    return;
                }
                final DriveContents driveContents = result.getDriveContents();

                // Perform I/O off the UI thread.
                new Thread() {
                    @Override
                    public void run() {
                        // write content to DriveContents
                        OutputStream outputStream = driveContents.getOutputStream();
                        Writer writer = new OutputStreamWriter(outputStream);
                        try {
                            writer.write(resultSet.toString());
                            writer.close();
                        } catch (IOException e) {
                            Log.e(TAG, e.getMessage());
                        }

                        MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                .setTitle("backup.txt")
                                .setMimeType("text/plain")
                                .setStarred(true).build();

                        // create a file on root folder
                        Drive.DriveApi.getRootFolder(mGoogleApiClient)
                                .createFile(mGoogleApiClient, changeSet, driveContents)
                                .setResultCallback(fileCallback);
                    //    Drive.DriveApi.requestSync(mGoogleApiClient).await();
                    }
                }.start();
            }
        };

final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
        ResultCallback<DriveFolder.DriveFileResult>() {
            @Override
            public void onResult(DriveFolder.DriveFileResult result) {
                if (!result.getStatus().isSuccess()) {
                    // showMessage("Error while trying to create the file");

                    return;
                }
                // showMessage("Created a file with content: " + result.getDriveFile().getDriveId());
                Toast.makeText(getBaseContext(), "Backup to cloud done", Toast.LENGTH_SHORT).show();
                //Toast.makeText(Myportfolio.this, "Created a file with content: " + result.getDriveFile().getDriveId(), Toast.LENGTH_LONG).show();
                Log.d("File Id: ", String.valueOf(result.getDriveFile().getDriveId()));

            }
        };


public class EditContentsAsyncTask extends AsyncTask<DriveFile, Void, Boolean> {


    @Override
    protected Boolean doInBackground(DriveFile... params) {
        DriveFile file = params[0];
        try {
            DriveApi.DriveContentsResult driveContentsResult = file.open(
                    mGoogleApiClient, DriveFile.MODE_WRITE_ONLY, null).await();

            if (!driveContentsResult.getStatus().isSuccess()) {
                return false;
            }
            DriveContents driveContents = driveContentsResult.getDriveContents();
            OutputStream outputStream = driveContents.getOutputStream();
            outputStream.write(resultSet.toString().getBytes());
            com.google.android.gms.common.api.Status status =
                    driveContents.commit(mGoogleApiClient, null).await();
            return status.getStatus().isSuccess();
        } catch (IOException e) {
            Log.e(TAG, "IOException while appending to the output stream", e);
        }

        return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (!result) {
            // showMessage("Error while editing contents");
            return;
        }
Log.d("Update: ", "Done");
        // showMessage("Successfully edited contents");
    }
}

final private ResultCallback<DriveApi.DriveIdResult> idCallback1 = new ResultCallback<DriveApi.DriveIdResult>() {
    @Override
    public void onResult(DriveApi.DriveIdResult result) {
        new RetrieveDriveFileContentsAsyncTask().execute(result.getDriveId());
    }
};

public class RetrieveDriveFileContentsAsyncTask extends AsyncTask<DriveId, Boolean, String> {
    @Override
    protected String doInBackground(DriveId... params) {
        String contents = null;
        DriveFile file = params[0].asDriveFile();
        DriveApi.DriveContentsResult driveContentsResult =
                file.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null).await();
        if (!driveContentsResult.getStatus().isSuccess()) {
           return null;
        }
        DriveContents driveContents = driveContentsResult.getDriveContents();
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(driveContents.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            contents = builder.toString();
        } catch (IOException e) {
            Log.e(TAG, "IOException while reading from the stream", e);
        }

        driveContents.discard(mGoogleApiClient);



        return contents;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (result == null) {
           // showMessage("Error while reading from the file");

            return;
        }
      //  restoregoogle=result;
        try {
            if (result == null) {
                return;
            }




            Toast.makeText(getBaseContext(), "Restored from cloud", Toast.LENGTH_SHORT).show();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
Log.d("Data from Cloud: ", result);

       // showMessage("File contents: " + result);
    }
}

0 个答案:

没有答案