2

Hi im a newbie in Android & java lang. i have this code that tells you how long have you been playing. the code works fine, except when the screen turns off or when the user press the power button (sleep mode) it stop working. can any one suggest a simple code to keep my time counting even when the screen is off or in sleep mode. Thanks...

public class test extends Activity 
{
    Handler mHandler = new Handler();

    Runnable mUpdateTime = new Runnable() 
    {
        public void run() 
        { 
            sec += 1;
            if(sec >= 60) 
            {
                sec = 0;
                min += 1;
                if (min >= 60) 
                {
                    min = 0;
                    hour += 1;
                }
            }
            playtime.setText(String.format("%02d:%02d:%02d", hour, min, sec));
            mHandler.postDelayed(mUpdateTime, 1000);
        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mHandler.postDelayed(mUpdateTime, 1000);
    }
}
Medo
  • 45
  • 3
  • 11
  • BTW, I think you solve your problem, but take a right answer) http://stackoverflow.com/questions/24686218/timer-stops-every-time-the-phone-sleeps – Jack Mar 20 '16 at 07:10

2 Answers2

0

I would suggest not counting the time, rather setting a start time and then subtracting that from the current to get the elapsed time.

Mike Park
  • 10,845
  • 2
  • 34
  • 50
0

A Chronometer widget might solve your problems.

I would advise against any solution where you might have to count during sleep mode, since that will kill the user's battery life.

Sam
  • 86,580
  • 20
  • 181
  • 179
ajpolt
  • 1,002
  • 6
  • 10