Mick
Mick

Reputation: 7947

Timer task only works when phone awake

I have an activity, called from an alarm broadcast receiver, which plays a notification sound every N seconds. This is achieved with the following code:

repeating_notification_sound_timer.schedule(ring_the_buzzer_task, 0, 1000 * N);

Early on in the onCreate function of the activity I have the following code:

pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
            wakeLock.acquire();

This all works perfectly well, so long as the phone was awake at the point when the alarm is triggered. However if the phone was asleep the notification sound gets played exactly once and never again. The program does not crash or report any errors. Its as if the repeating_notification_sound_timer could only be bothered to work once! Any ideas?

EDIT: Here is the code that sets the alarm in the first place:

static void set_alarm(long alarm_time_in_millis,Context cont,AlarmManager alarm_manager,String str)
{
    Intent launchIntent = new Intent(cont, to_call_when_alarm_goes_off.class);

    launchIntent.putExtra("string_passed_in_bundle", str);

    launchIntent.setAction(to_call_when_alarm_goes_off.CUSTOM_INTENT);

    PendingIntent pIntent = PendingIntent.getBroadcast(cont,0, launchIntent, 0);
    alarm_manager.cancel(pIntent);

    alarm_manager.set(AlarmManager.RTC_WAKEUP,alarm_time_in_millis, pIntent);
}

EDIT: In the manifest I have:

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />

Upvotes: 1

Views: 1591

Answers (2)

Jug6ernaut
Jug6ernaut

Reputation: 8325

You need to set your AlarmManager alarm to be of the wakeup veriaty, else the broadcast will wait to fire until your phone is wake up by something else.

Ether RTC_WAKEUP

or ELAPSED_REALTIME_WAKEUP

For specifics please provide your alarm code.

Upvotes: 1

CaseyB
CaseyB

Reputation: 25048

If you're wanting to have something that keeps track of timing over a long period of time or while the app is in the background you really need to use a Service.

Upvotes: 0

Related Questions