Android可继续上传到Google云端硬盘 [英] Android resumable upload to Google Drive

查看:149
本文介绍了Android可继续上传到Google云端硬盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试Android版的Drive API,以上传一个能够显示上传进度的文件,如果失败,文件大小可以恢复上传(文件大小> 30 MB)。

有以下问题:
正在上传将大尺寸文件下载到Google云端硬盘时出现错误
上传进度侦听器没有被解雇(Google驱动器API)
我能够获得上传进度,他们提到那些是可恢复的上传。但是,我没有看到任何代码寻找上传错误和恢复逻辑,因此,如果我杀了应用程序和恢复上传,它只是从头开始。



这是我的代码:

 公共类DriveScreen扩展BaseDriveActivity {
私人云端硬盘服务;
私有上下文上下文;
@Override
public void onConnected(Bundle connectionHint){
super.onConnected(connectionHint);
context = this;

//https://stackoverflow.com/questions/17429798/usingoauth2-deprecated
GoogleAccountCredential凭证= GoogleAccountCredential.usingOAuth2(this,Arrays.asList(DriveScopes.DRIVE_FILE));
credential.setSelectedAccountName(accountNameHERE);
service = new Drive.Builder(AndroidHttp.newCompatibleTransport(),new GsonFactory(),credential).build();
UploadFile();


public void UploadFile(){
AsyncTask< Void,Long,String> task = new AsyncTask< Void,Long,String>(){
java.io.File fileContent;
FileContent mediaContent;
com.google.api.services.drive.model.File正文;
com.google.api.services.drive.model.File文件;
私人ProgressDialog mDialog;
长mFileLen;

@Override
保护void onPreExecute(){
// TODO自动生成的方法存根
super.onPreExecute();
mDialog = new ProgressDialog(context);
mDialog.setMax(100);
mDialog.setMessage(上传);
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton(Cancel,new OnClickListener(){

@Override
public void onClick(DialogInterface arg0,int arg1){
// TODO Auto - 生成方法存根

}
});
mDialog.show();


FileUploadProgressListener实现MediaHttpUploaderProgressListener {
$ b $ @Override $ b $ public void progressChanged(MediaHttpUploader uploader)throws IOException {
Log.d Percent,String.valueOf(uploader.getProgress()));
switch(uploader.getUploadState()){
case INITIATION_STARTED:
System.out.println(Initiation Started);
break;
case INITIATION_COMPLETE:
System.out.println(Initiation Completed);
break;
case MEDIA_IN_PROGRESS:
System.out.println(正在上传);
System.out.println(Upload percentage:+ uploader.getProgress());
mDialog.setProgress((int)(uploader.getProgress()* 100));
break;
case MEDIA_COMPLETE:
System.out.println(Upload Completed!);
break;
case NOT_STARTED:
System.out.println(Upload Not Started!);
break;



$ @覆盖
保护字符串doInBackground(Void ... arg0){
try {
File folder = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
);
文件UPLOAD_FILE =新文件(文件夹,filePathHERE);
fileContent =新建文件(文件夹,filePathHERE);
mFileLen = fileContent.length();

InputStreamContent mediaContent2 = new InputStreamContent(application / zip,new FileInputStream(UPLOAD_FILE));
mediaContent2.setLength(UPLOAD_FILE.length());
body = new com.google.api.services.drive.model.File();
body.setTitle(fileContent.getName());
body.setMimeType(application / zip);
//字符串parentId = null;
// int x = Files.List.setQ(mimeType ='application / vnd.google-apps.folder'and title ='ShareHim');
//body.setParents (Arrays.asList(new ParentReference()。setId(uploadFile.getFileHostFolderId())));


$ b Files.Insert mInsert = service.files()。insert(body,mediaContent2); (mFileLen> 5 * 1024 * 1024)

)MediaHttpUploader uploader = mInsert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(false);
uploader.setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE);
uploader.setProgressListener(new FileUploadProgressListener());
file = mInsert.execute();
if(file!= null){

}
}
else {
mInsert.execute();
}
} catch(UserRecoverableAuthIOException e){
System.out.println(login error);
Log.d(Error,not login+ e);
} catch(IOException e){
e.printStackTrace();
}
返回null;


$ b保护无效onPostExecute(字符串结果){
mDialog.dismiss();
};
};
task.execute();


$ / code $ / pre
$ b $现在,它是通过块上传,我们从上次发送的块恢复上传。看到Google Drive在YouTube上谈到的第一印象是,可恢复的上传是自动处理的,但似乎并非如此。



我接近这个错误的方式吗?是否值得考虑使用DriveSyncAdapter上传文件作为替代? (对不好的代码,这只是一个测试)

解决方案

看起来你正在使用Java REST-ful API 。如果您使用Android特定的API,则全部为您处理。只需交出文件,API将根据需要进行恢复上传。请参阅创建文件


I am testing the Drive API for Android to upload a file that can show uploaded progress and be able to resume the upload if it fails (Files size > 30 MB.)

With the following questions: Uploading Downloading of large size file to Google Drive giving error, Upload progress listener not fired (Google drive API) I was able to get the upload progress and they mention those are resumable uploads. However, I don't see any code that looks for an upload error and resume logic, thus if I kill the application and "resume" the upload, it simply starts from the beginning.

This is my code:

public class DriveScreen extends BaseDriveActivity {
    private Drive service;
    private Context context;
    @Override
    public void onConnected(Bundle connectionHint) {
        super.onConnected(connectionHint);
        context = this;

        //https://stackoverflow.com/questions/17429798/usingoauth2-deprecated
        GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(this, Arrays.asList(DriveScopes.DRIVE_FILE));
        credential.setSelectedAccountName("accountNameHERE");
        service = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
        UploadFile();
    }

    public void UploadFile() {
        AsyncTask<Void, Long, String> task = new AsyncTask<Void, Long, String>() {
            java.io.File fileContent;
            FileContent mediaContent;
            com.google.api.services.drive.model.File body;
            com.google.api.services.drive.model.File file;
            private ProgressDialog mDialog;
            long mFileLen;

            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();
                mDialog = new ProgressDialog(context);
                mDialog.setMax(100);
                mDialog.setMessage("Uploading ");
                mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mDialog.setProgress(0);
                mDialog.setButton("Cancel", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // TODO Auto-generated method stub

                    }
                });
                mDialog.show();
            }

            class FileUploadProgressListener implements MediaHttpUploaderProgressListener {

                @Override
                public void progressChanged(MediaHttpUploader uploader) throws IOException {
                    Log.d("Percent ", String.valueOf(uploader.getProgress()));
                    switch (uploader.getUploadState()) {
                    case INITIATION_STARTED:
                        System.out.println("Initiation Started");
                        break;
                    case INITIATION_COMPLETE:
                        System.out.println("Initiation Completed");
                        break;
                    case MEDIA_IN_PROGRESS:
                        System.out.println("Upload in progress");
                        System.out.println("Upload percentage: " + uploader.getProgress());
                        mDialog.setProgress((int) (uploader.getProgress()*100));
                        break;
                    case MEDIA_COMPLETE:
                        System.out.println("Upload Completed!");
                        break;
                    case NOT_STARTED:
                        System.out.println("Upload Not Started!");
                        break;
                    }
                }
            }

            @Override
            protected String doInBackground(Void... arg0) {
                try {
                    File folder = Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_PICTURES
                        );
                    File UPLOAD_FILE = new File(folder, "filePathHERE");
                    fileContent = new File(folder, "filePathHERE");
                    mFileLen = fileContent.length();

                    InputStreamContent mediaContent2 = new InputStreamContent("application/zip", new FileInputStream(UPLOAD_FILE));
                    mediaContent2.setLength(UPLOAD_FILE.length());
                    body = new com.google.api.services.drive.model.File();
                    body.setTitle(fileContent.getName());
                    body.setMimeType("application/zip");
                    //String parentId = null;
                    //int x = Files.List.setQ("mimeType = 'application/vnd.google-apps.folder' and title = 'ShareHim'");
                    //body.setParents(Arrays.asList(new ParentReference().setId(uploadFile.getFileHostFolderId())));



                    Files.Insert mInsert = service.files().insert(body, mediaContent2);
                    if(mFileLen > 5 * 1024 * 1024)
                    {
                        MediaHttpUploader uploader = mInsert.getMediaHttpUploader();
                        uploader.setDirectUploadEnabled(false);
                        uploader.setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE);
                        uploader.setProgressListener(new FileUploadProgressListener());
                        file = mInsert.execute();
                        if (file != null) {

                        }
                    }
                    else {
                        mInsert.execute();
                    }
                } catch (UserRecoverableAuthIOException e) {
                    System.out.println("login error");
                    Log.d("Error", "not login " + e);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }


            protected void onPostExecute(String result) {
                mDialog.dismiss();
            };
        };
        task.execute();
    }
}

Now, it is uploading by chunks, but how can we resume the upload from the last chunk sent. My first impression after watching Google Drive talks on youtube was that the resumable upload was handled automatically, but it doesn't seem to be the case.

Am I approaching this the wrong way? Is it worth considering using a DriveSyncAdapter to upload a file as an alternative? (Sorry for the bad code, this is just a test)

解决方案

It looks like you are using the Java REST-ful API. If you use the Android-specific API, this is all handled for you. Just hand over the file, and the API will do resumable upload as appropriate. See creating files.

这篇关于Android可继续上传到Google云端硬盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆