安卓消息机制(单个线程倒计时结束后重启的方法)

111 阅读1分钟
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) {
                //启动子线程发送Message
                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;
                }
        }
    }