0

I want that when I press button for cdtimer 1, it resumes while other pauses and vice versa. I tried to do that with below code. But the other timer also runs parallel with the running timer. Please help me with pausing and resuming the timers and to run only timer at a time and pausing other.

public void p1Start(View a)
{
    if(flag==0) {
        p2.setTextColor(Color.parseColor("#ffffff"));
        p2.setBackgroundColor(Color.parseColor("#00bcd4"));

        p1.setTextColor(Color.parseColor("#3f51b5"));
        p1.setBackgroundColor(Color.parseColor("#303F9F"));

        reverseTimer(300-1, p2);

        cd2.start();
        cd1.cancel();
        flag=1;
    }
}

public void p2Start(View b)
{
    if(flag==1) {
        p1.setTextColor(Color.parseColor("#ffffff"));
        p1.setBackgroundColor(Color.parseColor("#00bcd4"));

        p2.setTextColor(Color.parseColor("#3f51b5"));
        p2.setBackgroundColor(Color.parseColor("#303F9F"));

        reverseTimer(300-1, p1);

        cd1.start();
        cd2.cancel();
        flag=0;
    }
}

public void reverseTimer(long Seconds, final TextView tv){

     cd1 =  new CountDownTimer(Seconds* 1000+1000, 1000) {

        public void onTick(long millisUntilFinished) {
            s1=millisUntilFinished/1000;
            int seconds = (int) (millisUntilFinished / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;
            tv.setText("" + String.format("%02d", minutes)
                    + ":" + String.format("%02d", seconds));
        }

        public void onFinish() {
            tv.setText("Completed");
        }
    };

    cd2 =  new CountDownTimer(Seconds* 1000+1000, 1000) {

        public void onTick(long millisUntilFinished) {
            s2=millisUntilFinished/1000;
            int seconds = (int) (millisUntilFinished / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;
            tv.setText("" + String.format("%02d", minutes)
                    + ":" + String.format("%02d", seconds));
        }

        public void onFinish() {
            tv.setText("Completed");
        }
    };
}
  • Instead of using thread. achieve this using handler by posting message to main thread to update ui at your desire time. For pause and resume, check out this link ans - http://stackoverflow.com/questions/40103742/android-update-textview-every-second – Keyur Thumar Mar 13 '17 at 04:51
  • You should basically used handler that would remove runnable once you want it to stop like what @keyur9779 had given – MuTiny Mar 13 '17 at 05:31

0 Answers0