简体   繁体   中英

How to stop Thread in Android?

I had a thread which executes a function in every 30 minutes, so I used a combination of handler and runnable thread ( like postdelayed,removemessages ).At that time I couldn't find any way to stop thread.I tried hander. Removemessages() and hander.removeCallbacks(Runnable) but couldn't help..

I will suggest you to use TimerTask instead of Thread . Here you can cancel & restart the TimerTask .

I suggest you to use alarmmanager. There is a problem with timertask. Sometimes the service where the timertask is initiated might be destroyed. If the service is not running timertask will also become disable. It happen frequently when the device is in idle state. So the best solution is to use alarmmanager which trigger an alarm in every 30 minutes whether your device is in idle state or not. You only need to initiate the alarm when you first start the application and need to re-initiate when the device is rebooted. You can use a broadcast receiver to get message when your device is rebooted.

To stop a thread in java, you need to call thread.interrupt(); method.

timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
                                         if(your condition to stop thread)
                                         {
                                            timer.cancel();
                                          }else
                                         {
                                             \\ your code
                                          }
                                      }
            }, 0, 1800000);

use timer inside....it will solve your problem

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