Android定时器和Handler用法实例分析
本文实例讲述了Android定时器和Handler用法。分享给大家供大家参考。具体分析如下:
一、环境:
主机:WIN8
开发环境:Android Studio
二、定时器使用示例:
初始化:
//定时器 private Timer Timer_Work = new Timer(); //工作间隔,单位:ms private final int INTERVAL_WORK = 5000;
创建定时器线程:
/** * 构造函数 */ public Config() { //生成配置信息 generate_config_info(); //创建定时线程 Timer_Work.schedule(new Task(), INTERVAL_WORK, INTERVAL_WORK); // 定时任务 }
新建任务:
/** * 定时器线程定时工作 */ private class Task extends TimerTask { @Override public void run() { generate_config_info(); } }
三、定时器和Handler组合工作,更新UI示例(定时器线程不能直接更新UI):
定时器任务:
/** * 定时器线程定时工作 */ 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 message = new Message(); message.what = 1; handler.sendMessage(message); } } }
Handler处理信息:
private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: { System.out.println("sdk打开视频准备"); video(-224); break; } } super.handleMessage(msg); } };
四、Handler和Runnable组合产生线程示例:
延时200ms调用runnable
handler.postDelayed(runnable, 200);
产生线程:
Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { try { int videoBitrate = anychatSDK.QueryUserStateInt(userID, AnyChatDefine.BRAC_USERSTATE_VIDEOBITRATE); if (videoBitrate > 0) { handler.removeCallbacks(runnable); mOtherView.setBackgroundColor(Color.TRANSPARENT); } handler.postDelayed(runnable, 200); } catch (Exception e) { e.printStackTrace(); } } };
希望本文所述对大家的Android程序设计有所帮助。
赞 (0)