简体   繁体   中英

Android cancel Thread

I am doing a simple Async operation with Android, but since I want to execute the action couple of times, I am not using AsyncTask, I instead use Thread/Runnable mechanism with Handler to handle messages and staff. But at one point when I need to execute the second operation, I need to cancel the previous operation if it is still active.

I have something like this:

private void exec() {
    new Thread(new Runnable() {
    public void run() {
    mBind.exec(3);
    }
  }).start();
}

Then in exec(int a) I have an interation like:

for(int i = 0; i<=res.lenght; i++) {
   updateGui();
}

But at one point the exec() method is called for second time, and the gui is updated with the previous results too (I need only the results from the new (2nd) request).

I know there is way to do this with FutureTask and play with cancel() or with Thread's 'throw ThreadDead' exception, but I am just curious if I can do it the same way I started in the first place.

thanks!

What I have understand from your question is that you want to cancel the currently running thread if the new thread started.

This you can do by calling Thread's interrupt() method, this will interrupt the currently running thread, and throws the InterruptedException.

Thread t1 = null;
private void exec() {
    t1 = new Thread(new Runnable() {
    public void run() {
    mBind.exec(3);
    }
  }).start();
}

Before calling exec, call t1.interrupt().

Feels a bit dirty, but could you save the name of the most recently activated Thread and check for it in your Handler ? Something like:

private static final int MESSAGE_UPDATE_COMPLETE = 0;
private String threadName;

private void exec() {
    Thread thread = new Thread() {
        public void run() {
            // do stuff
            ...
            Message msg = Message.obtain();
            msg.what = MESSAGE_UPDATE_COMPLETE;
            msg.obj = this.getName();
            handler.sendMessage(msg);
        }
    };
    thread.start();
    threadName = thread.getName();
}
...
private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        switch(msg.what){
        case MESSAGE_UPDATE_COMPLETE:
            if (threadName.equals((String)msg.obj)) {
                // do UI update
            }
            break;
        ...
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM