This example describes the Android timer and handler usage. Share to everyone for your reference. The specific analysis is as follows:
First, the environment:
Host: WIN8
Development environment: Android Studio
Second, the use of the Timer sample:
Class
Timer
Private Timer timer_work = new timer ();
Working interval, unit: Ms
private Final int interval_work = 5000;
To create a timer thread:
/**
* Constructor/
public
Config () {
//Generate configuration Information
generate_config_info ();
Create a timed thread
timer_work.schedule (new Task (), interval_work, interval_work);
Timed Task
}
New task:
/**
* Timer thread timed work * *
Private class task extends TimerTask {
@Override public
void Run () {
Generate_config_info ();
}
Three, timer and handler combination work, update UI example (timer thread cannot update UI directly):
Timer Task:
/**
* Timer thread timed work
/Private class task extends TimerTask {
@Override public
void Run () {
if (get_ state () = = Enum_state.free)
{
Connect ("10.58.1.59", 8906);
}
if (get_state () = = enum_state.connect_success)
{
login ("Tiantian", "");
}
if (get_state () = = enum_state.login_success)
{
enter_room (1, "");
}
if (get_state () = = enum_state.enter_room_success) {message:
= new Message ();
Message.what = 1;
Handler.sendmessage (message);}}
Handler Processing information:
Private Handler Handler = new Handler () {public
void Handlemessage (msg) {
switch (msg.what) {
case 1:
{
System.out.println ("SDK open video Preparation");
Video ( -224);
break;
}
}
Super.handlemessage (msg);
}
;
The handler and runnable combinations generate threads Sample:
Delay 200ms Call runnable
Handler.postdelayed (runnable, 200);
To generate a thread:
Handler Handler = new Handler ();
Runnable Runnable = new Runnable () {
@Override public
void Run () {
try {
int videobitrate = Anychatsdk.que Ryuserstateint (UserID, anychatdefine.brac_userstate_videobitrate);
if (videobitrate > 0)
{
handler.removecallbacks (runnable);
Motherview.setbackgroundcolor (color.transparent);
}
Handler.postdelayed (runnable);
catch (Exception e) {
e.printstacktrace ();}}}
;
I hope this article will help you with your Android program.