Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android系統教程 >> Android開發教程 >> Android實現計時與倒計時的幾種方法

Android實現計時與倒計時的幾種方法

編輯:Android開發教程

方法一

Timer與TimerTask(Java實現)

public class timerTask extends Activity{

    private int recLen = 11;     
    private TextView txtView;     
    Timer timer = new Timer();     

    public void onCreate(Bundle savedInstanceState){     
        super.onCreate(savedInstanceState);     

        setContentView(R.layout.timertask);     
        txtView = (TextView)findViewById(R.id.txttime);     

        timer.schedule(task, 1000, 1000);       // timeTask     
    }        

    TimerTask task = new TimerTask() {     
        @Override 
        public void run() {     

            runOnUiThread(new Runnable() {      // UI thread     
                @Override 
                public void run() {     
                    recLen--;     
                    txtView.setText(""+recLen);     
                    if(recLen < 0){     
                        timer.cancel();     
                        txtView.setVisibility(View.GONE);     
                    }     
                }     
            });     
        }     
    };     
}

方法二

TimerTask與Handler(不用Timer的改進型)

public class timerTask extends Activity{  

   
    private int recLen = 11;     
    private TextView txtView;     
    Timer timer = new Timer();     

    public void onCreate(Bundle savedInstanceState){     
        super.onCreate(savedInstanceState);     

        setContentView(R.layout.timertask);     
        txtView = (TextView)findViewById(R.id.txttime);     

        timer.schedule(task, 1000, 1000);       // timeTask     
    }        

    final Handler handler = new Handler(){     
        @Override     
        public void handleMessage(Message msg){     
            switch (msg.what) {     
            case 1:     
                txtView.setText(""+recLen);     
                if(recLen < 0){     
                    timer.cancel();     
                    txtView.setVisibility(View.GONE);     
                }     
            }     
        }     
    };     

    TimerTask task = new TimerTask() {     
        @Override     
        public void run() {     
            recLen--;     
            Message message = new Message();     
            message.what = 1;     
            handler.sendMessage(message);     
        }     
    };     
}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved