I am building an android application and I want an hour gap between two lines of code, I use thread.sleep() method with 1800000 seconds but it makes my application irresponsive and closed the execution. Any suggestions or help would be beneficial for me.
CodePudding user response:
Try running the code on a different thread:
class MyThread implements Runnable {
public void run() {
try {
Thread.sleep(1800000000);
} catch (InterruptedException err) {
//handle interruption
}
System.out.print("world!");
}
}
class Main {
public static void main(String[] args) {
System.out.print("Hello ");
Thread t = new Thread(new MyThread());
t.start();
}
}
This will allow the main thread to continue running tasks while the second one is waiting in the background.
CodePudding user response:
As @GaneshPokale suggested above, WorkManager is the best solution for your case.
- Don't stop Main thread(=UI thread): Sleeping in the Main thread will stop your entire app, and it will lead you to ANR, which will make your app killed if your app is stopped more than 5 sec.
- In this case, you need to create another thread. WorkManager is one of the solutions for such cases, which need to wait a long time. You can also use AlarmManager or some other ways.