如何定期检查AsyncTask的doInBackground()内的isCancelled()并在需要时返回?

时间:2015-01-27 13:32:03

标签: android android-asynctask timertask

我看到并阅读了很多帖子和文档。我明白一个可以插入几个isCancelled();在一些代码块之间。如果更大的工作负载不能分成像Url抓取的部分那么呢?

我尝试了这个虚拟项目试图找到一个解决方案:当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()的值,但我找不到一种方法可以在那之后动作。任何的想法 ?或任何其他方式?

Ty

1 个答案:

答案 0 :(得分:1)

取消方法是公开的,因此您可以覆盖它。在自定义实现中,您可以先:调用基本版本,然后中止任何挂起的http连接。您必须小心,因为可能会从GUI线程调用cancel,但我认为它应该可以工作。