0

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);
Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111
Simon Schubert
  • 2,010
  • 19
  • 34

1 Answers1

1

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.)

Torid
  • 4,176
  • 1
  • 28
  • 29
  • Torid is right. In current Java thread implementation, there is no safe way to stop a running thread outside the thread. See Java doc: http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html, all the stop()/destroy() call have been deprecated. The solution is to break your readXML() call into a series small chunk of work. In your thread, you need to check isCancelled() after each chunk of work, and end the thread if the work has been cancelled. – dongshengcn Jul 10 '11 at 14:40