Android Studio 入门 线程篇

private TextView textView;
static boolean showtime=true;
private android.os.Handler handler=new android.os.Handler(){
public void handleMessage(Message msg){
switch (msg.what){
case 0x123:
textView.setText(msg.obj.toString());break;
case 0x1234:
textView.setText("OK?");break;
default:break;
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);

Button button=(Button)findViewById(R.id.button_top);
textView=(TextView)findViewById(R.id.text_top);
final Thread threadShowTime=new Thread(new Runnable() {
@Override
public void run() {

while (true) {
try {
Thread.sleep(1000);
Message msg = new Message();
msg.what = 0x123;
msg.obj = new Date().toString();
Message msg1=new Message();
msg1.what=0x1234;
if(showtime)
handler.sendMessage(msg);
else
handler.sendMessage(msg1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
});

button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
threadShowTime.start();
if (showtime) {
showtime = false;
String s=String.valueOf(showtime);
Toast.makeText(FirstActivity.this,s,Toast.LENGTH_SHORT).show();
} else {
threadShowTime.interrupt();
showtime = true;
String s=String.valueOf(showtime);
Toast.makeText(FirstActivity.this,s,Toast.LENGTH_SHORT).show();
}


}
});

转载于:https://www.cnblogs.com/dreammaker-K/p/6605843.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值