我正在使用以下代码测试Google Drive API:
public void UploadVideo() {
Drive.DriveApi.newDriveContents(gac).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
public void onResult(final DriveApi.DriveContentsResult result) {
new Thread() {
public void run() {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream("/sdcard/my_video.avi"));
bos = new BufferedOutputStream(result.getDriveContents().getOutputStream());
final int BUFFER_SIZE = 8192;
byte buffer[] = new byte[BUFFER_SIZE];
int n;
while ((n = bis.read(buffer, 0, BUFFER_SIZE)) != -1)
bos.write(buffer, 0, n);
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(bis != null) {
try {
bis.close();
} catch (IOException e) {
}
}
if(bos != null) {
try {
bos.close();
} catch (IOException e) {
}
}
}
MetadataChangeSet mcs = new MetadataChangeSet.Builder()
.setMimeType("video/x-msvideo")
.build();
IntentSender is = Drive.DriveApi.newCreateFileActivityBuilder()
.setActivityTitle("File name to save")
.setInitialMetadata(mcs)
.setInitialDriveContents(result.getDriveContents())
.build(gac);
try {
startIntentSenderForResult(is, 54321, null, 0,0,0);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
}.start();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (54321 == requestCode) {
if(resultCode == RESULT_OK) {
DriveId writtenFileID = data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
DriveFile writtenFile = writtenFileID.asDriveFile();
writtenFile.getMetadata(gac)
.setResultCallback(new ResultCallback<DriveResource.MetadataResult>() {
public void onResult(DriveResource.MetadataResult metadataResult) {
Metadata md = metadataResult.getMetadata();
String s = md.getTitle() + "\n"
+ md.getMimeType() + "\n"
+ md.getFileSize();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
});
}
}
}
问题是,即使关闭APP,这也会异步工作,因此无法停止上传。我正在测试一个大小约为250MB的文件,但我上面的所有代码都立即运行到结束,包括onActivityResult()回调方法。我的互联网非常慢,我可以在五分钟左右的时间内看到我的GDrive上传完整的文件。
有没有办法停止上传或同步上传方法?