Android之CountDownTimer

本文探讨了在OpenCamera项目中发现的Android CountDownTimer类的使用,它是Google封装的倒计时工具,内部基于Handler实现。此外,还提到了结合CountDownTimer与防止AsyncTask超时的场景,以及AsyncTask和Queue的使用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在看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)
		{
		}

		@Override
		protected void onPreExecute()
		{
		}

		// 参数对应AsyncTask中的第一个参数
		@Override
		protected Void doInBackground(Void... params)
		{
			// 后台执行,比较耗时的操作都可以放在这里
			return null;
		}

		// 参数对应AsyncTask中的第三个参数(也就是接收doInBackground的返回值)
		@Override
		protected void onPostExecute(Void v)
		{
			// 相当于Handler 处理UI的方式,在这里面可以使用在doInBackground 得到的结果处理操作UI
		}

		// 参数对应AsyncTask中的第二个参数
		@Override
		protected void onProgressUpdate(Void... values) {
			// 可以使用进度条增加用户体验度。 此方法在主线程执行
			super.onProgressUpdate(values);
		}
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值