我使用async http android library loopj 实现文件上传服务。它具有以下简化的实现
class MyService extends IntentService {
private CompletionService<NoResultType> mEcs;
private ExecutorService mExec;
private final int THREADS_NUM = 5;
private final AsyncHttpClient aClient = new AsyncHttpClient();
public interface UploadListener{
void uploadFailed(final int position, int errorCode );
void didUpload(final int position);
}
UploadListener myUploadListener;
MyService(){
// Init CompletionService and ExecutorService is here
mExec = Executors.newFixedThreadPool(THREADS_NUM);
mEcs = new ExecutorCompletionService<NoResultType>(mExec);
}
myUploadListener = new UploadListener{
void uploadFailed(final int position, int errorCode ){
if(isCriticalError(errorCode)){
aClient.cancelRequests(getApplicationContext(),true); // Cancel Upload process
mExec.shutdownNow(); // Stop Execution of upload tasks
}
}
} // myUploadListener
protected void onHandleIntent(Intent intent) {
// Init tasks here
ArrayList<File> fileList = gerFileList()
ArrayList<UploadTask> tasks = new List
for (File file : fileList) {
UploadTask yt1 = new UploadTask(file.getId(), file);
tasks.add(yt1);
}
for (UploadTask t : tasks) {
mEcs.submit(t); // Start Task
}
} // onHandleIntent
class UploadTask implements Callable<NoResultType> {
public UploadTask(int position, MFile file) {
mPosition = position;
mFile = file;
}
@Override
public NoResultType call() throws Exception {
aClient.post(getApplicationContext(),url,params,new AsyncHttpResponseHandler{
public void onFailure(Throwable e, String response) {
myUploadListener.uploadFailed(mPosition, getCode(response));
}
} ); // aClient.post
} // call()
} // UploadTask
} // MyService
这种实现的逻辑很简单:每当上传由于致命错误而失败时,立即取消执行其他上传任务。问题是它终止了任务的执行,但它并没有终止在已经启动的任务中上传文件。
例如,上传任务Starts => aClient.post(file)
。上传任务已取消。但是,尽管调用aClient.post(file)
aClient.cancelRequests(getApplicationContext(),true);
仍会停留
任何想法?谢谢。
答案 0 :(得分:1)
谷歌搜索了一段时间后,我想出了一个虚拟的解决方案: 要关闭请求进程,只需调用
// aClient is an instance of AsyncHttpClient(SyncHttpClient)
aClient.getHttpClient().getConnectionManager().shutdown();
它就像一个魅力:)