赞
踩
“`JAVA
public class MainActivity extends Activity {
Handler handler;
private TextView tv;
int i = 0;
public boolean isstop = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); // 定时器的三种实现方法 // ----------------------------------------------------------------------------- // 第一种:采用Handler与线程的sleep(long)方法 handler = new Handler() { public void handleMessage(android.os.Message msg) { tv.setText(i++ + ""); // 开启定时器线程 new Thread(new MyThread()).start(); }; }; } public void start(View view) { isstop = false; // 开启定时器线程 new Thread(new MyThread()).start(); } // 停止 public void stop(View view) { isstop = true; } class MyThread implements Runnable { @Override public void run() { if (!isstop) { // TODO Auto-generated method stub try { Thread.sleep(1 * 1000); Message msg = new Message(); msg.what = 1; handler.sendMessage(msg); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
}
“
“`java
public class MainActivity extends Activity {
Handler handler;
private TextView tv;
int i = 0;
Runnable runnable;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); handler = new Handler(); runnable = new Runnable() { @Override public void run() { // TODO Auto-generated method stub // 要做的事情 tv.setText(i++ + ""); handler.postDelayed(runnable, 2 * 1000); } }; } public void start(View view) { // 开启定时器线程 handler.postDelayed(runnable, 2 * 1000);//两秒后执行一次runnable的 run() 方法. } // 停止 public void stop(View view) { handler.removeCallbacks(runnable); }
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。