I would like to make a thread in android that runs in the back. The thread keeps checking the time with a while loop and if it matches it does something. This all works great. But the app is not responsive, as if i'm not running a thread at all. The while still blocks everything. I don't understand why.
code of the thread:
public class AlarmThread implements Runnable {
LocalTime beginTime;
LocalTime endTime;
public AlarmThread(LocalTime beginTime, LocalTime endTime) {
this.beginTime = beginTime;
this.endTime = endTime;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
currentTime = java.time.LocalTime.now();
if(currentTime.isAfter(beginTime) && currentTime.isBefore(endTime)){
sendNotification();
}
}
}
the activity:
public void onButtonClickerDatepicker(View v) throws IOException {
LocalTime beginTime = java.time.LocalTime.of(binding.simpleTimePicker.getHour(), binding.simpleTimePicker.getMinute());
LocalTime endTime = java.time.LocalTime.of(binding.simpleTimePicker2.getHour(), binding.simpleTimePicker2.getMinute());
alarmThread = new AlarmThread(beginTime, endTime);
alarmThread.run();
}
Calling Thread.start()
to start a thread otherthan Thread.run()
. And what's more your AlarmThread is not a Thread but a Runnable. So you can start it by code below:
private Thread workerThread = new Thread(new AlarmThread(start, end))
...
...
workerThread.start()
I recommend you use HandlerThread for flexibility
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.