Set time variable on Back button

Asked

Viewed 62 times

1

You guys, good night. I need a little help, I have the following code. Because I need to stop Thread when the back button is clicked.

private void timeGame() {

    t = new Timer();
    t.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            //runOnUiThread
            runOnUiThread(new Runnable() {
                @SuppressLint("SetTextI18n")
                @Override
                public void run() {

                    if (timeCounter > 0){

                        timeCounter--;
                       textoTime.setText((Integer.toString((timeCounter))));

                    }else{

                        t.cancel();
                        startActivity(new Intent(QuestionsSolo.this, GameOver.class));
                        QuestionsSolo.this.finish();

                    }


                    }

            });

        }
    }, 1000, 1000);

}

@Override
public void onBackPressed() {
//funcionando, ficou assim.    
t.cancel();
startActivity(new Intent(QuestionsSolo.this, TypeFragmentSolo.class));
}

}

  • No need to put (solved) the Guil question. The fact that you approve an answer means that the question has been resolved. Hug!

  • 1

    Malz, I didn’t know. Hugs bro. Thanks again. kkk

1 answer

1


Option 1

You can use a volatile as an attribute for control.

private volatile boolean run = true;

...
private void timeGame() {
 ...

   if (timeCounter > 0 && run){ // <-- atributo de controle

      timeCounter--;
      textoTime.setText((Integer.toString((timeCounter))));

   }else{

      t.cancel();// <-- cancela se o atributo for false
      startActivity(new Intent(QuestionsSolo.this, GameOver.class));
      QuestionsSolo.this.finish();

    }

Then in the onBackPressed() you change:

@Override
public void onBackPressed() {
    run = false;
}

This way it will cancel when the attribute run for false.

Option 2

Instead of putting the Timer within the function timeGame()

private void timeGame() {
      final Timer t = new Timer();

...

You insert this Timer as a class attribute:

Timer t;

and in the function you change to:

 private void timeGame() {
      t = new Timer();

  ...

With this you will be able to cancel within the onBackPressed():

@Override
public void onBackPressed() {
   t.cancel();
}

I haven’t tested any of them, but I believe both options work.

  • 1

    It’s Andrei, Bleeza? Just you to save me, Hahahha.. Both options don’t work and they work, what do you mean?! They stop the counter, but block the back button. The counter stops but it doesn’t come back. But there, Tarammmm.. I sent an Intente after t.Cancel(). playing pro Fragment that wanted, ai got top. kkkk

  • @Guildraco ah! You can believe it! But why does it lock right?... How good it worked out?! =)

  • @Guildraco I’ll do some tests later! Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.