简体   繁体   English

如何在Android中停止Thread?

[英]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. 我有一个线程每30分钟执行一次函数,因此我使用了处理程序和可运行线程的组合(例如postdelayed,removemessages)。当时我找不到任何方法来停止线程。 Removemessages() and hander.removeCallbacks(Runnable) but couldn't help.. Removemessages()和hander.removeCallbacks(Runnable),但无济于事。

I will suggest you to use TimerTask instead of Thread . 我建议您使用TimerTask而不是Thread Here you can cancel & restart the TimerTask . 在这里您可以取消并重新启动TimerTask

I suggest you to use alarmmanager. 我建议您使用Alarmmanager。 There is a problem with timertask. timertask有问题。 Sometimes the service where the timertask is initiated might be destroyed. 有时启动计时器任务的服务可能会被破坏。 If the service is not running timertask will also become disable. 如果服务未运行,timertask也将被禁用。 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. 因此,最好的解决方案是使用alarmmanager,该设备每30分钟触发一次警报,无论您的设备是否处于空闲状态。 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(); 要在Java中停止线程,您需要调用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 在内部使用计时器...。它将解决您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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