我需要从服务器下载大量数据,最少需要10秒。以下是我使用AsyncTask类进行下载的代码。当用户在下载操作进行时点击主页按钮,我想无条件取消下载操作。问题是…我执行cancel()方法,但它并没有取消下载操作。我发现在logcat视图中仍在运行操作,即使我退出了应用程序。我只想停止执行doInBackground()方法。请指导/帮助我。
点击下载按钮:
在onPause()方法中...
点击下载按钮:
dwnldTask = new DownloadTask ();
dwnldTask.execute(SERVER_URL);
这里是Asynctask类:
class DownloadTask extends AsyncTask<String, Void, Object>{
private Object response = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
displaying progress dialog on UI
}
@Override
protected Object doInBackground(String... params) {
try{
DataConnection dc = new DataConnection();
this.response = dc.connectToServer(params[0]);
if(isCancelled()){
return null;
}
}catch (Exception e) {
if(isCancelled()){
return null;
}
e.printStackTrace();
showToastMSG(e.getMessage());
}
return this.response ;
}
@Override
protected void onPostExecute(Object response) {
super.onPostExecute(response);
if(response != null ){
successfully downloaded... go to next activity
}
cancel progress dialog here
}
}
在onPause()方法中...
@Override
protected void onPause() {
super.onPause();
if(dwnldTask != null && dwnldTask.getStatus() == AsyncTask.Status.RUNNING){
dwnldTask.cancel(true);
}
cancel the progress dialog if it is showing
}
这里是另一个名为DataConnection的类中的方法...
public Object connectToServer(String url) throws Exception{
HttpGet request = new HttpGet(url);
request.addHeader("accept","application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity httpEntity = response.getEntity();
InputStream responseInputStream = httpEntity.getContent();
return myUtilObject.convertInputStreamToString(responseInputStream);
}
dwnldTask
设置为任务对象了吗?你确定你调用了onStop()
吗? - andr