public class MainActivity extends AppCompatActivity {
private Button btn_start;
private TextView tv_time;
private MyThread thread=null;
public int num=10;
public static final int WHAT=1;
private MyHandle handle=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start= (Button) findViewById(R.id.btn_start);
tv_time= (TextView) findViewById(R.id.tv_time);
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(thread==null){
thread=new MyThread();
thread.start();
}
}
});
if(handle==null){
handle=new MyHandle();
}
}
class MyThread extends Thread{
@Override
public void run() {
super.run();
while (!Thread.interrupted()){
while (num>=0){
Message message= handle.obtainMessage(WHAT,String.valueOf(num));
handle.sendMessage(message);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
num--;
}
if(num<0){
thread.interrupt();
thread=null;
num=10;
}
}
}
}
class MyHandle extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case WHAT:
tv_time.setText(msg.obj.toString());
break;
}
}
}