Roman Marius
Roman Marius

Reputation: 476

Android timer that counts when app is closed

I have an activity in which I want to track the time elapsed between two actions(for example startAction and endAction). I've used the following code to implement a timer that increments every 500 ms after the user presses the button for startAction:

TextView dayTimer = (TextView)findViewById(R.id.tvDayTimer);
long startTime;
class DayTimer extends TimerTask {

             @Override
             public void run() {
                 BBCAndroid.this.runOnUiThread(new Runnable() {

                  
                     public void run() {
                        long millis = SystemClock.elapsedRealtime() - startTime;
                        int seconds = (int) (millis / 1000);
                        int minutes = seconds / 60;
                        seconds     = seconds % 60;

                        dayTimer.setText(String.format("%d:%02d", minutes, seconds));
                     }
                 });
             }
        };


      startDayButton.setOnClickListener(new View.OnClickListener() {
            
            public void onClick(View v) {
                // TODO Auto-generated method stub
                
                            startTime = SystemClock.elapsedRealtime();
                        timer.schedule(new DayTimer(),  0,500);
                        LoginResult.DayState = 1;
                        startDayButton.setEnabled(false);
                        endDayButton.setEnabled(true);
            }
        });

Now my problem is that, if I exit the application the timer stops. How can I make it run even when the user is out of the app? In summary, I need a timer that counts even if the app is closed.

Upvotes: 0

Views: 3676

Answers (3)

marccgcom
marccgcom

Reputation: 73

I resolved your problem using the life cycle.

If the application is not destroyed you can count time by applying your code to the onPause or onStop.

But you have to advertise the user when he is going to destroy the app.

This was my solution to continue receiving messages with my app running in the foreground and to avoid excessive power consumption.

Read about the lifeCycle here:

http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

I hope this can be useful.

Upvotes: 1

You can start a Service and it will be up and running even if your application is closed.

Here is a good tutorial.

Upvotes: 2

Luke Taylor
Luke Taylor

Reputation: 9599

You could create a Service or create a thread in which your timer runs. This wouldn't destroy your timer when you app is closed.

I hope this helps.

Upvotes: 1

Related Questions