Android编程:定时器和Handler的使用



Android编程:定时器和Handler的使用


本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明.


环境:

主机: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)