Search code examples
androidmultithreadingtimecountdownpause

how to pause thread in buttonOnClick


I have a thread that countdown from 30 to 1 and a button.I have start the thread but I don't know how to pause that thread within buttonOnClick.This is my code for your reference.Thank you for your help.

(how to pause thread in buttonOnClick)

int n;
TextView box2;


Handler handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        String string = box2.getText().toString();
        int num = Integer.parseInt(string);
        num = num - 1;
        string = Integer.toString(num);
        box2.setText(string);


    }

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

}



class Allthread extends Thread { //backgroud task

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (i = 30; i > 0; i--) {
            try {
                Thread.sleep(1000);
                //handler.sendMessage(handler.obtainMessage());
                handler.sendMessage(handler.obtainMessage());

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }


}



public void buttonOnClick(View view) {  
    //do something when enter is clicked
    Button enter = (Button) findViewById(R.id.button);

    TextView box1 = (TextView) findViewById(R.id.box1);

    n++; 
    box1.setText("number" + n);

    if(n==1){ 
        Allthread T1 = new Allthread();
        T1.start();//start the thread
    }

    // I want pause thread here.





    }
}

Solution

  • See this link How to pause/resume thread in Android?