Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 定時器demo

Android 定時器demo

編輯:關於Android編程

注意點:
1:必須創建一個新對象來同步
2:New Thread中需要用post對原線程中的對象進行操作
3:在New Thread中用 wait進行定時

package com.example.appc; 
 
import android.os.Bundle; 
import android.app.Activity; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 
 
 
public class MainActivity extends Activity { 
    Button startButton ; 
    TextView minuteTextView ; 
    //contorl bool   www.2cto.com
    static boolean sign = false; 
    Clock c = new Clock(); 
 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
 
        startButton = (Button)findViewById(R.id.button1); 
        minuteTextView = (TextView)findViewById(R.id.textView1);        
        startButton.setOnClickListener(new MyButtonListener()); 
    } 
    class MyButtonListener implements OnClickListener{ 
         
        public void onClick(View v) { 
            sign = !sign; 
            if(sign == false) return; 
            new Thread(new Runnable() {          
                public void run() { 
                    while( sign ){ 
                        try{ 
                            synchronized (c) { 
                                minuteTextView.post(new Runnable() {                                 
                                    public void run() { 
                                        minuteTextView.setText("99"); 
                                    } 
                                });                          
                                c.wait(500L); 
                                minuteTextView.post(new Runnable() { 
                                    public void run() { 
                                        minuteTextView.setText("0"); 
                                    }  
                                }); 
                                c.wait(500L); 
                            } 
                        }catch(InterruptedException e){ 
                        } 
                    } 
                } 
            }).start(); 
        } 
         
    } 
    public class Clock { 
        int justATmp = 0; 
    } 

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