Android使用Thread加Handler实现计时与保持屏幕唤醒不熄灭

4e48 10年前

用到了两个小知识点:一是使用Thread加Handler实现计时,二是控制屏幕唤醒不熄灭。

首先是计时,首先我使用单纯的Handler来实现计时,代码如下:

Handler handler = new Handler();      Runnable runnable = new Runnable() {          @Override          public void run() {              timeSec ++;              mTimeCount.setText("" + timeSec);              handler.postDelayed(this, 1000);          }      };

但是这样有个弊端,当我的主线程里有Thread.Sleep延时操作时,这个时候计时就会暂停。所以需要在另外一个Thread里来进行计时:


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;              }          }      }

在应用destory的时候得把wakeLock给release掉:


  @Override      protected void onDestroy() {          super.onDestroy();          keepScreenOn(Main.this, false);      }