简体   繁体   中英

how to stop a thread in Android?

I'm using a Thread to initialize some resources while displaying a splash screen with a progress bar, and sometimes start a different activity (for result).

At first I used AsyncTask, which works great, except that I found out that I can't use another one(Android 1.5) so I had to use a Thread.

currently, my code looks like this:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splashscreen);
    m_progressBar = (ProgressBar) findViewById(R.id.progressBar);
    m_progressBar.setMax(10);
    // start the Init process
    Thread thread = new Thread(initTask);
    thread.start();

As Thread.stop() is deprecated, and I can't use Thread.interrupt(), If I press the back key, I can't stop the thread from starting a new Activity.

Any suggestions?

Stopping a thread requires the cooperation from the thread in question. The general idea is to send the thread a signal, and it regularly checks for that signal and then stops itself. The simplest "signal" is a simple boolean field that it checks.

First, you can use multiple AsyncTasks at the same time, there is no limit on that. What was the problem?

Update: Indeed before 1.6 AsyncTasks were executed serially on same background thread, one after another.

Second, threading in java is cooperative - you can not kill a thread, but rather you have to notify it about your intent to be stopped and it then stops it itself (ie exits the run method).

To signal it to stop, just have a boolean field running=true which thread checks in it's main loop. When running==false thread exits the run() method.

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