Need to notify user when for example user clicks button and in
onClick method program starts some long-time process. Need to have some solution which will do your task in background.
Handler is very good solution for this problem.
If you will not use such approach then user will see that program appears to hang.
When you create an object from the
Handler class, it processes
Messages and
Runnable objects associated with the current thread
MessageQueue. the message queue holds the tasks to be executed in FIFO (First In First Out) mannser. you will need only ine
Handler per activity where the background thread will communicate with to update the UI.
The Handler is associated with the thread from which it’s been created
We can communicate with the Handler by two methods:
- Messages.
- Runnable objects.
I am going to show you using runnable Object..
public class Expense extends Activity {
Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.expense);
ctx = this;
handler.post(message);
}
private Runnable message = new Runnable() {
//@Override
public void run() {
//do task needed
}
};
}
Sending Messages in a timely manner:
we can use handlers to send messages or post runnables at time intervals using
The following methods:
- handler.sendEmptyMessageAtTime(int what,long uptimeMillis):sends an
empty message at a specific time in milli-seconds, can be defined by using the
SystemClock.uptimeMillis() method to get the time since the device boot
in milli-seconds and concatinating to it.
- handler.sendEmptyMessageDelayed(int what,long delayMillis):sends an
empty message after a certain amount of time in milli-seconds.
- handler.sendMessageAtTime(Message msg,long uptimeMillis).
- handler.sendMessageDelayed(Message msg,long delayMillis).
- handler.postAtTime(Runnable r,long uptimeMillis).
- handler.postAtTime(Runnable r,Object token,long uptimeMillis):posts a
runnable with an object as a distinguishing token.
- handler.postDelayed(Runnable r,long delayMillis)
Removing Call backs:
If you want to remove a runnable or a message from the message queue, you can use the following methods:
- handler.removeCallbacks(Runnable r).
- handler.removeCallbacks(Runnable r,Object token).
- handler.removeCallbacksAndMessages(Object token).
- handler.removeMessages(int what).
- handler.removeMessages(int what,Object object)
suppose if you want to execute block of statement at regular interval.laet say after every 10 seconds..
public class Expense extends Activity {
Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.expense);
ctx = this;
handler.post(message);
}
private Runnable message = new Runnable() {
//@Override
public void run() {
//do task needed
handler.postDelayed(message,10000) ;
}
};
}
Comments
Post a Comment