0

I'm developing an Android game, but I'm facing the problem, that when the user pauses the game and then wants to continue by restarting the app, instead of accessing it from RAM, everytime the same timer get's instanciated again.

Here's my timer:

public void createTimers() {
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//Stuff here
                    }
                });
            }
        }, 0, 1000 / 60);

So, whenever the user start's the app (or restarts it, while it's still in RAM) this is being executed:

Timer timer = new Timer();
createTimers();

This way the player can abuse the timer by pressing the hombe button, then start the app over and over again, because each time there will be more timerTasks! In Android I got these:

@Override
protected void onPause() {
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
}

methods, but if I use timer.cancel() in the onPause, the whole Timer named timer is cancelled and a start of the app, while it's still in RAM throws an exception.

I also tried Handlers and Runnables, that recursively call themselves, but as I do some heavy calculations in the loop, it slowed down the loop, unlike here, where it's a fixed rate! Help pls :S

Malwinder Singh
  • 6,644
  • 14
  • 65
  • 103
  • http://stackoverflow.com/questions/2098642/pausing-stopping-and-starting-resuming-java-timertask-continuously – Apurva Mar 09 '15 at 17:03
  • I read through that, but it doesnt really help the problem. My problem is not the timer itself, it's that I have to create the timer somewhen(in my case in the onCreate method), which leads to the problem, that starting that app again, I then have 2 timers running! – user3646267 Mar 09 '15 at 18:07
  • Now tried it with ScheduledExecutorService, ending in the same result. – user3646267 Mar 09 '15 at 18:28

1 Answers1

0

I now made it work with the ScheduledExecutorService, which can be shutdown when "onPause" gets triggered, and just get's instantiated again, when "onResume" is triggered.