Android之CountDownTimer

来源:互联网 发布:网络图绘制软件 编辑:程序博客网 时间:2024/05/22 08:01

最近在看OpenCamera的源码,表示受益很深,项目地址:https://github.com/almalence/OpenCamera

源码中大量使用了CountDownTimer,Android已经帮封装好的一个类,提供倒计时这个功能

倒计时自己实现可以使用handler,点开源码,发现Google也是使用Handler实现的,源码上有一段注释

new CountDownTimer(30000, 1000) {      public void onTick(long millisUntilFinished) {          mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);      }       public void onFinish() {          mTextField.setText("done!");      }   }.start();

很简单,一个TextView不断显示剩下的时间, new CountDownTimer(30000, 1000)中,第一个参数表示总时间,第二个参数表示间隔时间。意思就是每隔一秒会回调一次方法onTick,onTick里返回剩余多少时间,然后30秒之后会回调onFinish方法

唉,这么好的东西,只恨自己知道的太晚了


- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

防止AsyncTask任务长时间没有响应,相当于Http里的timeOut,与CountDownTimer组合使用,模拟代码

顺便记录一些AsyncTask,Queue 的使用

Queue<Task> taskQueue = new ConcurrentLinkedQueue<>();public void updateTask(){Task t= null;t = new Task(ApplicationScreen.instance);t.execute();taskQueue.add(t);new CountDownTimer(1000, 1000){public void onTick(long millisUntilFinished){}public void onFinish(){try{Task t= null;t = taskQueue.poll();if (t != null && t.getStatus() != AsyncTask.Status.FINISHED){t.cancel(true);}} catch (Exception e){Log.e("error: ", e.getMessage());}}}.start();}/* AsyncTask比Handler更轻量级一些,适用于简单的异步处理。 * 定义了三种泛型类型 Params,Progress和Result。 * Params 启动任务执行的输入参数,比如HTTP请求的URL。 * Progress 后台任务执行的百分比。 * Result 后台执行任务最终返回的结果,比如String。 */private class Task extends AsyncTask<Void, Void, Void>{public Task(Context context){}@Overrideprotected void onPreExecute(){}// 参数对应AsyncTask中的第一个参数@Overrideprotected Void doInBackground(Void... params){// 后台执行,比较耗时的操作都可以放在这里return null;}// 参数对应AsyncTask中的第三个参数(也就是接收doInBackground的返回值)@Overrideprotected void onPostExecute(Void v){// 相当于Handler 处理UI的方式,在这里面可以使用在doInBackground 得到的结果处理操作UI}// 参数对应AsyncTask中的第二个参数@Overrideprotected void onProgressUpdate(Void... values) {// 可以使用进度条增加用户体验度。 此方法在主线程执行super.onProgressUpdate(values);}}




0 0
原创粉丝点击