开发者

Android Cancel long operation (Asynctask,thread...?)

I tried AsyncTask, Thread and Handler but i don't get it.

The method readXML() takes about 1-2 minutes and i only need a way to cancel this operation. All the solutions I've found were for short time operations (set flag, check flag and break).

Edit

protected class InitTask extends AsyncTask<Context, Integer, String> {

    @Override
    protected String doInBackground( Context... params ){
        try{
            preparing = true;
            readXML();
            preparing = false;
        } catch( Exception e ){
            Log.i("test", e.getMessage() );
       开发者_运维问答 }
        return "COMPLETE!";
    }

    @Override
    protected void onCancelled(){               
        super.onCancelled();
    }

}

// ....
_initTask = new InitTask();
_initTask.execute(this);

// ....
_initTask.cancel(true);


Your problem is that onCancelled is only invoked after doInBackground returns. So you need to check for isCancelled from within your readXML operation. See extract from docs (from http://developer.android.com/reference/android/os/AsyncTask.html) below...

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜