AsyncTask没有取消android中长时间运行的操作
作者:互联网
我必须从服务器下载大量数据.下载至少需要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);
}
解决方法:
我同意Ran – 你没有写下代码:
myUtilObject.convertInputStreamToString
但我猜测你在输入流上循环使用你预先确定其大小的缓冲区(可能使用BufferedReader?) – 在这个循环中你应该检查你的异步线程的停止条件 – isCancelled()就是一个很好的例子.
如果线程被取消,循环应该停止,即:
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 1024);
while ((line = rd.readLine()) != null && !isCancelled())
{
total.append(line);
}
标签:android,android-asynctask,cancellation 来源: https://codeday.me/bug/20190529/1179702.html