我必须从服务器下载大量数据。下载至少需要 10 秒。这是我使用 asyntask 类下载的代码。如果用户在下载操作进行时单击主页按钮,我想无条件取消下载操作。问题是......我正在执行 cancel() 方法,但它没有取消下载操作。即使我退出应用程序,我也看到该操作在 logcat 视图中在后台运行。我只想停止执行 doInBackground() 方法。请指导/帮助我。
点击下载按钮:
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);
}