大家好,欢迎来到IT知识分享网。
第一种,Handler+ thread
public class MainActivity extends Activity {
TextView textView;
int time;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
textView.setText(msg.arg1 + "");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.test_time);
textView.setText(time + "");
new Thread() {
@Override
public void run() {
int times = 0;
while (true) {
try {
Thread.sleep(1000);
Message message = new Message();
message.arg1 = times;
times++;
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
这种明显的是使用了另外一个线程,在android开发中,速度是很重要的,开启线程都是需要进行消耗大量资源的,android不必web,他的资源有限,所以我们在不必要的时候,不要开启线程,结果是:
结果很简单
第二种:Handler + postDelyed
TextView textView;
int time = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.test_time);
System.out.println("Main Name : "
+ Thread.currentThread().getName());
handler.postDelayed(runnable, time);
}
Handler handler = new Handler();
Runnable runnable = new Runnable() {
int i = 0;
@Override
public void run() {
System.out.println("Name : "
+ Thread.currentThread().getName());
textView.setText(i + "");
handler.postDelayed(this, time);
i++;
}
};
结果打印如下:
可以看出,这种的定时效果是在主线程中的并且实在MessageQuence中进行实现的:
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
这是android的源码,他确实没有启动线程
第三种:Handler+Timer+TimerTask
TextView textView;
int time = 10000;
int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.test_time);
System.out.println("Main Name : "
+ Thread.currentThread().getName());
// handler.postDelayed(runnable, time);
timer.schedule(timerTask,0,10000);
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
textView.setText(i++ + "");
}
};
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("Name : "
+ Thread.currentThread().getName());
Message message = new Message();
handler.sendMessage(message);
}
};
打印图:
可以看出,这个也是自己启动了一个线程,实在线程中进行定时的
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/11978.html