php_nub_qq
php_nub_qq

Reputation: 16055

Timer stops every time the phone sleeps

I'm creating this incredibly simple app, since I'm just starting with Android and I have no experience with Java what so ever. Anyhow, all I have is a timer and a button. Obviously the button starts the timer which counts down from 60 ( 1 minute ) and then vibrates when it's done. All worked fine up until the point I decided to press the lock screen button to put the phone to sleep. I found out that the timer in my app stops going until I unlock the phone. This also happens if I set the auto sleep time to less than 60 seconds and the phone falls asleep on it's own. My question is - how can I have that chronometer running even when the screen is not active?

Upvotes: 1

Views: 2231

Answers (1)

Josef E.
Josef E.

Reputation: 2219

You need to make this using BroadCastRecievers for system-calls. (Related Helpful question)

You can also play off the life-cyles of the Activity using the PowerManager.


Example using PowerManager:

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

    // If the screen is off then the device has been locked
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    boolean isScreenOn = powerManager.isScreenOn();

    if (!isScreenOn) {
        // The screen has been locked
        // Continue your timer
    }
}

Upvotes: 1

Related Questions