当前位置:操作系统 > 安卓/Android >>

Android 定时器demo

注意点:
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.zzzyk.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; 
    } 

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,