博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android定时,延时,倒计时源码
阅读量:2391 次
发布时间:2019-05-10

本文共 5590 字,大约阅读时间需要 18 分钟。

 三种常用的定时器 

Handler mHandler = new Handler();Runnable r = new Runnable() {                    @Override                    public void run() {                            //do something                                			                            //每隔1s循环执行run方法                            mHandler.postDelayed(this, 1000);                                                }};主线程中调用:mHandler.postDelayed(r, 1000);//延时1000毫秒后启动mHandler.removeCallbacks(r);  //停止计时
Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            if (msg.what == 1){                //do something            }            super.handleMessage(msg);        }    };    Timer timer = new Timer();    TimerTask timerTask = new TimerTask() {        @Override        public void run() {            Message message = new Message();            message.what = 1;            handler.sendMessage(message);        }    }; 主线程中调用:timer.schedule(timerTask,1000,500);//延时1s,每隔500毫秒执行一次run方法
Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            if (msg.what == 1){                //do something            }            super.handleMessage(msg);        }    };    class MyThread extends Thread {//这里也可用Runnable接口实现        @Override        public void run() {            while (true){                try {                    Thread.sleep(1000);//每隔1s执行一次                    Message msg = new Message();                    msg.what = 1;                    handler.sendMessage(msg);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }    }主线程中调用:new Thread(new MyThread()).start();

三种延时执行的快捷方法: 

new Handler().postDelayed(new Runnable() {        @Override        public void run() {              //do something          }       }, 1000);    //延时1s执行
timer = new Timer();                 timer.schedule(new TimerTask() {                                       @Override                    public void run() {                          //do something                    }                },1000);//延时1s执行
new Thread(new MyThread()).start();        new Thread(new Runnable() {            @Override            public void run() {                try {                    Thread.sleep(1000);//延时1s                    //do something                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }).start();

 

范例:android源码一个猜数字游戏 猜大猜小带计时.rar

package com.example.guessgame;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.*;public class MainActivity extends ActionBarActivity {	private final int TIME_ALL=20;	private int Time=TIME_ALL;	private TextView info;	private EditText input;	private Button button;	private int target;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        info = (TextView)findViewById(R.id.info);        input = (EditText)findViewById(R.id.input);        button = (Button)findViewById(R.id.button);                button.setOnClickListener(new View.OnClickListener() {						@Override			public void onClick(View view) {				// TODO Auto-generated method stub				if(button.getText().toString().equals("OK")){					mHandler.removeCallbacks(r);  //停止计时					if(input.getText().toString().equals(""))						return;					int tmp = Integer.parseInt(input.getText().toString());					if(tmp == target){						info.setText("恭喜你,猜对了");						button.setText("再来一次!");					}					else if(tmp < target)						info.setText("猜小了,请重试");					else 						info.setText("猜大了,请重试");						}				else					newGame();			}		});        newGame();    }    Handler mHandler = new Handler();                 Runnable r = new Runnable() {                    @Override                    public void run() {                            //do something                            Time--;	                            if(Time==0)                            {                            		info.setText("(计时"+TIME_ALL+"秒,当前:"+Time+"),你已经超时了。");                            }                            else if(Time>0)                            {                            		info.setText("(计时"+TIME_ALL+"秒,当前:"+Time+")请输入1-100之间的数字:");                            }                       			                            //每隔1s循环执行run方法                            mHandler.postDelayed(this, 1000);                                                }                };                    private void newGame(){    	    	Time=TIME_ALL;    	mHandler.postDelayed(r, 1000);//延时1000毫秒后启动    	info.setText("(计时"+TIME_ALL+"秒,当前:"+Time+")请输入1-100之间的数字:");    	input.setText("");    	button.setText("OK");    	target = (int)((Math.random())*99 + 1);    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}

 

转载地址:http://xcaab.baihongyu.com/

你可能感兴趣的文章
使用Apache Common的FileUpload的一点点注意事项
查看>>
arduino连接热敏打印机的资料
查看>>
用zxing生成条形码
查看>>
如何将OpenShift与eclipse集合使用
查看>>
Build Your Own PaaS on RHEL 6
查看>>
关于JAX-RS的导引阅读
查看>>
Markdown编辑器editor.md的使用
查看>>
FileServlet supporting resume and caching and GZIP
查看>>
spring boot etag header example
查看>>
关于大数据的两个大分支
查看>>
spring boot Websocket
查看>>
关于企业到个人的转账
查看>>
Angular4中调用js代码
查看>>
JAVA8-用lamda表达式和增强版Comparator进行排序
查看>>
spring boot 2.0 使用Hikari连接池——号称java平台最快的,替换druid
查看>>
GnuPG Java Wrapper API - Sample code
查看>>
HTTP Cache 总结及Nginx Cache配置
查看>>
基于现有 TensorFlow 模型构建 Android 应用
查看>>
Building an Ionic OCR App with Tesseract
查看>>
Spring boot with Apache Hive
查看>>