0

i need to create a timer (with start and stop function), that continue to work also in background, because: - my app have 2 activity switchable via intent, so if i return to activity 1 the timer must continue to work, and if i return to activity 2 (that of the timer) the "textview" must update the timer that is continuing to work - if i put the app in background, the timer must continue to work. how can i do this? i've found this, but i'm not sure that it can do what i need: http://examples.javacodegeeks.com/android/core/os/handler/android-timer-example/

Thanks!

D Ferra
  • 1,223
  • 3
  • 12
  • 21

2 Answers2

1

For making the timer working in background, use Asynctask. Then if necessary, you can switch activities in the foreground from doinBackground function of Asynctask using RunOnUiThread method (or separate thread if you so desire).

SoulRayder
  • 5,072
  • 6
  • 47
  • 93
0

Standard Java way to use timers via java.util.Timer and java.util.TimerTask works fine in Android, but you should be aware that this method creates a new thread.

You may consider using the very convenient Handler class (android.os.Handler) and send messages to the handler via sendMessageAtTime(android.os.Message, long) or sendMessageDelayed(android.os.Message, long). Once you receive a message, you can run desired tasks. Second option would be to create a Runnable object and schedule it via Handler's functions postAtTime(java.lang.Runnable, long) or postDelayed(java.lang.Runnable, long).

For a repeating task:

new Timer().scheduleAtFixedRate(task, after, interval); For a single run of a task:

new Timer().schedule(task, after);

task being the method to be executed after the time to initial execution (interval the time for repeating the execution)

Handler:

private final int interval = 1000; // 1 Second
private Handler handler = new Handler();
Private Runnable runnable = new Runnable(){
    public void run() {
        Toast.makeText(MyActivity.this, "C'Mom no hands!", Toast.LENGTH_SHORT).show();
    }
};
...
handler.postAtTime(runnable, System.currentTimeMillis()+interval);
handler.postDelayed(runnable, interval);

Message:

private final int EVENT1 = 1; 
private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {         
        case Event1:
            Toast.makeText(MyActivity.this, "Event 1", Toast.LENGTH_SHORT).show();
            break;

        default:
            Toast.makeText(MyActivity.this, "Unhandled", Toast.LENGTH_SHORT).show();
            break;
        }
    }
};

...

Message msg = handler.obtainMessage(EVENT1);
handler.sendMessageAtTime(msg, System.currentTimeMillis()+interval);
handler.sendMessageDelayed(msg, interval);
Hassaan Rabbani
  • 2,469
  • 5
  • 30
  • 55