多线程handler的使用——3秒钟更换一次标题
对于多线程我们已经有了些许认识,现在就对其进一步的学习应用吧。把它用在android中实现标题的更换(3秒更换一次):
只需要编写Activity实现即可,这里有两种方法,可以根据自己习惯选择使用(个人较喜欢第一种):
(1)Runnable:
[html]
public class MainActivity extends Activity {
private int count = 1;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
updateTitle();
break;
default:
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new TitleThread()).start();
}
protected void updateTitle() {
setTitle("my bolg" + count++);
}
class TitleThread implements Runnable {
@Override
public void run() {
while (true) {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
(2)Timer:
[html]
public class TimerActivity extends Activity {
private int count=1;
private Handler handler=new Handler(){
public void handleMessage(android.os.Message msg){
switch(msg.what){
case 1:
updateTitle();
break;
default:
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Message message=new Message();
message.what=1;
handler.sendMessage(message);
}
}, 1000,3000);
}
protected void updateTitle() {
setTitle("hello"+(count++));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_timer, menu);
return true;
}
}
补充:web前端 , HTML 5 ,