
[英]how to check isCancelled() regularly in doInBackground() method
[英]How to periodically check isCancelled() inside doInBackground() of AsyncTask and return if needed ?
我看到并阅读了许多文章和文档。 我知道可以插入一些isCancelled(); 在一些代码块之间。 无法将Url fetching分解成更大的工作量又如何呢?
我尝试了这个虚拟项目以尝试找到解决方案:当asynctask工作时,我想定期检查isCancelled()并跳过doInBackground()中剩下的所有内容。
我尝试了这个:
@Override
protected Void doInBackground(Void... params) {
strUrlBase = "http://www.legorafi.fr/2012/12/20/portrait-benoit-le-fameux-ami-noir-de-tous-les-racistes/";
if (fgDebugLocal){Log.i(tagLocal, tagLocal + "strUrlBase = " + strUrlBase);};
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (isCancelled()) {
if (fgDebugLocal){Log.e(tagLocal, tagLocal + "timer asyncTask : isCancelled true" );};
timer.cancel();
return;
} else {
if (fgDebugLocal){Log.e(tagLocal, tagLocal + "timer asyncTask : isCancelled FALSE" );};
}
}
},0, 100);
for (int i = 0; i<15; i++ ) {
HttpURLConnection urlConnection = null;
try {
url = new URL(strUrlBase);
https = (HttpURLConnection) url.openConnection();
https.setDoOutput(true);
urlConnection = https;
if (urlConnection.getInputStream() != null){ // Crash there :(
inputStream = new BufferedInputStream(urlConnection.getInputStream());
reader = new BufferedReader(new InputStreamReader(inputStream));
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current=reader.read())!=-1){
baf.append((byte)current);
}
strJson = new String (baf.toByteArray());
if (fgDebugLocal){Log.i(tagLocal, tagLocal + "check le gorafi number "+i+" - " + strJson.substring(0, 100));};
https.disconnect();
} else {
if (fgDebugLocal){Log.i(tagLocal, "urlConnection.getInputStream() != null");};
fgErrorConn = true;
varResultRequest = -1;
}
} catch (IOException e) {
if (fgDebugLocal){Log.i(tagLocal, "IOException = "+e.getMessage());};
fgErrorPb = true;
varResultRequest =0;
//publishProgress(100);
}
}
varResultRequest = 1;
return null;
}
timertask可以正确检测isCancelled()的值,但是在此之后我找不到方法。 任何想法 ? 或其他方式?
泰
Cancel方法是公共的,因此您可以覆盖它。 在您的自定义实现中,您可以首先:调用基本版本,然后中止任何未决的http连接。 您必须谨慎,因为cancel可能会从GUI线程中调用,但是我想它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.