These two days work relatively busy, there is no time to update the blog. Today is a rare idle, summed up the previous write a demo, with two small knowledge points: First, the use of thread plus handler to achieve timing, the second is to control the screen wake does not go off.
The first is the timing, first I use simple handler to achieve timing, the code is as follows:
Handler Handler = new Handler (); Runnable Runnable = new Runnable () { @Override public void Run () { timesec + +; Mtimecount.settext ("" + timesec); Handler.postdelayed (this, +); } };
But there is a drawback, when my main thread has thread.sleep delay operation, this time will be paused. So the timing needs to be done in another 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 minutes or less mtimecount.settext ("Total time:" + timesec + "SEC"); } else if (Timesec < 3600) {//1 hours following case int minutes = TIMESEC/60; int second = timesec% 60; Mtimecount.settext ("Total time:" + minutes + "min" + Second + "SEC"); } else {int hours = timesec/3600; int minutes = (timesec-hours * 3600)/60; int second = timesec% 60; Mtimecount.settext ("Total time:" + hours + "when" + minutes + "min" + Second + "SEC"); }} super.handlemessage (msg); } };
So when the UI is blocking, although our mtimecount this textview is not updated in real time, the timing function is still in progress, and when the UI thread's Thread.Sleep () ends, it is updated.
Here's a look at the logic to keep the screen awake:
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;}} }
You have to release the Wakelock when applying destory:
@Override protected void OnDestroy () { Super.ondestroy (); Keepscreenon (Main.this, false); }
Android uses thread plus handler to achieve timing and keep screen wake-up not extinguished