Handler in Android
Overview
Handler allows you to send Message and process Runnable objects which are associated with the thread of a Message Queue.
Steps to create a Handler with Message
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
char c = s.charAt(i[0]);
bottomText.append(String.valueOf(c)); //bottomText is a TextView
i[0]++;
}
};
final Timer timer = new Timer();
TimerTask taskEverySplitSecond = new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(0);
if (i[0] == length - 1) {
timer.cancel();
}
}
};
timer.schedule(taskEverySplitSecond, 1, 500);
The above code throws a warning "This Handler class should be static" replace the code with the below code.
final Handler handler = new Handler(msg -> {
char c = s.charAt(i[0]);
bottomtext.append(String.valueOf(c)); //bottomText is a TextView
i[0]++;
return false;
});
final Timer timer = new Timer();
TimerTask taskEverySplitSecond = new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(0);
if (i[0] == length - 1) {
timer.cancel();
}
}
};
timer.schedule(taskEverySplitSecond, 1, 500);
Steps to create Handler with postDelayed()
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(MainActivity.this, LoginPage.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
}, 5000);
Comments
Post a Comment