Android使用线程做开始暂停

代码:

      

package com.example.liu.mytesta.home.pause;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.liu.mytesta.R;
import com.example.liu.mytesta.app.BaseActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MyPauseActivity extends BaseActivity {

    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.button)
    Button button;

    Handler handler=new Handler();
    int num=0;
    boolean mainFlag=false;
    boolean isPause=true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_my_pause);
        ButterKnife.bind(this);
        init();
    }

    @OnClick({ R.id.button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.button:
                isPause=!isPause;//暂停时开始,开始时暂停
                if (!isPause){
                    button.setText("暂停");
                }else {
                    button.setText("开始");
                }
                break;
        }
    }

    private void init() {
        myThread();
    }

    private void myThread() {
        new Thread(){
            @Override
            public void run() {
                super.run();
                mainFlag=true;
                while (mainFlag) {
                    if (!isPause) {
                        num++;
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                textView.setText(num+"");
                            }
                        });
                    }
                }
            }
        }.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (num!=0) {
            isPause = false;
            button.setText("暂停");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isPause=true;
        button.setText("开始");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mainFlag=false;
    }

    @Override
    public int setBaseView() {
        return R.layout.activity_my_pause;
    }

    @Override
    public boolean showTitle() {
        return true;
    }

    @Override
    public String setTitleText() {
        return "线程暂停开始";
    }
}

 

你可能感兴趣的:(Android线程)