Can i use this code inside a service for calling a method with delay or Handler()
should only be used inside a UI
thread ?
What is the best way for calling a method with delay inside a service
?
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 10000ms
socket.emit("CancelTravel");
}
}, 10000);
A Handler allows communicating back with UI thread from other background thread . This is useful in android as android doesn't allow other threads to communicate directly with UI thread. A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.
In android Handler is mainly used to update the main thread from background thread or other than main thread. There are two methods are in handler. Post() − it going to post message from background thread to main thread using looper.
Handler is a class which allows you to send and handle Messages and Runnables from thread's MessageQueue. Basically it works the following way: Client initializes Handler and Looper (so the whole infrastructure is now ready to use) Client sends messages to Handler.
The main difference between Handler and Thread is that a handler is a function or a method that is capable of performing a specific task while a thread is a small, lightweight execution unit within a process.
Handler()
only should be use inside a UI thread ?
Yes Handler()
usefull only on UI
thread and if you want use on normal thread, you need to implement looper
Sample code
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 10000ms
socket.emit("CancelTravel");
}
}, 5000);
You can also use Timer
A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.
Sample Code
new Timer().schedule(new TimerTask() {
@Override
public void run() {
//Do something after 10000ms
socket.emit("CancelTravel");
}
}, 10000);
what is preferred way for calling a method with delay inside a service?
Read Timertask
or Handler
You can use delay in Service like this:
private Handler handler = null;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
handler = new Handler();
...
}
...
// from inside your child thread
handler.post(new Runnable() {
@Override
public void run() {
//your code goes here
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With