标签:android wakelock 计时 thread handler
这两天工作比较忙,没有时间更新博客。今天难得闲下来,总结一下之前写的一个Demo,用到了两个小知识点:一是使用Thread加Handler实现计时,二是控制屏幕唤醒不熄灭。
首先是计时,首先我使用单纯的Handler来实现计时,代码如下:
Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { timeSec ++; mTimeCount.setText("" + timeSec); handler.postDelayed(this, 1000); } };
new Thread(new TimeThread()).start(); final Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: timeSec++; if (timeSec < 60) { // 1分钟以下情况 mTimeCount.setText("总耗时:" + timeSec + "秒"); } else if (timeSec < 3600) { // 1小时以下情况 int minutes = timeSec / 60; int second = timeSec % 60; mTimeCount.setText("总耗时:" + minutes + "分" + second + "秒"); } else { int hours = timeSec / 3600; int minutes = (timeSec - hours * 3600) / 60; int second = timeSec % 60; mTimeCount.setText("总耗时:" + hours + "时" + minutes + "分" + second + "秒"); } } super.handleMessage(msg); } };这样UI在阻塞时,虽然我们的mTimeCount这个TextView没有实时更新,但是计时函数还是在进行的,当UI线程的Thread.Sleep()结束时,就会更新。
下面看一下保持屏幕唤醒的逻辑:
private static PowerManager.WakeLock wakeLock;
public static void keepScreenOn(Context context, boolean on) { if (on) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "==KeepScreenOn=="); wakeLock.acquire(); } else { if (wakeLock != null) { wakeLock.release(); wakeLock = null; } } }
@Override protected void onDestroy() { super.onDestroy(); keepScreenOn(Main.this, false); }
Android使用Thread加Handler实现计时与保持屏幕唤醒不熄灭
标签:android wakelock 计时 thread handler
原文地址:http://blog.csdn.net/zhoumushui/article/details/41964147