zoukankan      html  css  js  c++  java
  • AndroidTimer使用(三)补充篇

     

    Android 的Timer 一般如下面所写

    Timer timer = new Timer();  
    TimerTask task = new TimerTask() {  
        public void run() {  
            Message message = new Message();  
            message.what = 1;  
            handler.sendMessage(message);  
      
        }  
      
    };  
    final Handler handler = new Handler() {  
      
        public void handleMessage(Message msg) {  
            switch (msg.what) {  
            case 1:  
                Log.e("Timer", "Timer");  
                update();  
                break;  
            }  
            super.handleMessage(msg);  
        }  
      
    };  
    protected void onDestroy() {  
        if (timer != null) {  
            timer.cancel();  
            timer = null;  
        }  
        super.onDestroy();  
    }  

    最重要一点是timer.schedule(task, 1000, 5000);如果设置为timer.schedule(task, 5000)是不会工作的。

    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        this.setContentView(R.layout.main);  
                                   timer.schedule(task, 1000, 5000);  
                    }  

    但更好的方法是通过下面的代码

    private Handler handler = new Handler();  
      
    private Runnable runnable = new Runnable() {  
      
        public void run() {  
            update();  
            handler.postDelayed(this, 1000);  
        }  
      
    };  

    开始Timer

    handler.postDelayed(runnable, 1000);  

    停止Timer

    handler.removeCallbacks(runnable); 
  • 相关阅读:
    DOM
    ES6的export和import
    JavaScript:Location
    垃圾回收机制之一:标记删除算法
    KnockoutJS:
    package.json
    2016/7/27
    requirejs:研究笔记
    postmessage/cors跨域postMessage、xhr2和xmldomain
    javascript:算法之数组sort排序
  • 原文地址:https://www.cnblogs.com/xuewater/p/2594668.html
Copyright © 2011-2022 走看看