AsyncHttpClient
为了拥有能够取消它的同步版本,我在主线程上做所有事情。以前我正在运行它,AsyncTask
一旦AsyncHttpClient.post()
被调用,它AsyncTask
就会完成,我无法跟踪AsyncHttpClient
实例。
SyncHttpClient
不允许我取消上传,所以我知道我必须使用AsyncHttpClient
并进行适当的更改。
以下是我上传文件的课程,该文件使用AsyncHttpClient
并允许取消:
public class AsyncUploader {
private String mTitle;
private String mPath;
private Callback mCallback;
public void AsyncUploader(String title, String filePath, MyCallback callback) {
mTitle = title;
mPath = filePath;
mCallback = callback;
}
public void startTransfer() {
mClient = new AsyncHttpClient();
RequestParams params = new RequestParams();
File file = new File(mPath);
try {
params.put("title", mTitle);
params.put("video", file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mClient.setTimeout(50000);
mClient.post(mContext, mUrl, params, new ResponseHandlerInterface() {
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
// TODO convert instream to JSONObject and do whatever you need to
mCallback.uploadComplete();
}
}
@Override
public void sendProgressMessage(int bytesWritten, int bytesTotal) {
mCallback.progressUpdate(bytesWritten, bytesTotal);
}
@Override
public void sendFailureMessage(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
mCallback.failedWithError(error.getMessage());
}
});
}
/**
* Cancel upload by calling this method
*/
public void cancel() {
mClient.cancelAllRequests(true);
}
}
这是您可以运行它的方式:
AsyncUploader uploader = new AsyncUploader(myTitle, myFilePath, myCallback);
uploader.startTransfer();
/* Transfer started */
/* Upon completion, myCallback.uploadComplete() will be called */
要取消上传,只需调用cancel()
:
uploader.cancel();