tags:

views:

196

answers:

1

I changed AlarmController.java in ApiDemo a little bit, so I want the alarm not to go off when the phone is sleeping by using AlarmManager.RTC.

        Intent intent = new Intent(AlarmController.this, RepeatingAlarm.class);
        PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this,
                0, intent, 0);

        // We want the alarm to go off 30 seconds from now.
        long firstTime = SystemClock.elapsedRealtime();
        firstTime += 15*1000;

        // Schedule the alarm!
        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC, //AlarmManager.ELAPSED_REALTIME_WAKEUP,
                        firstTime, 15*1000, sender);

The receiver code is like below:

public class RepeatingAlarm extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Log.d("DEBUG", "In RepeatingAlarm.onReceive, intent=" + intent);
        Toast.makeText(context, R.string.repeating_received, Toast.LENGTH_SHORT).show();
    }
}

I ran the modified app, but I still see many log messages as below after the phone wento sleep (the screen was black):

D/DEBUG ( 1390): In RepeatingAlarm.onReceive, intent=Intent { flg=0x4 cmp=com.example.android.apis/.app.RepeatingAlarm (has extras) }

This means the flag AlarmManager.RTC didn't work. Can someone tell me why?

Thanks.

+2  A: 

Since you are using elapsedRealtime to get the alarm start time, I think you need to use the ELAPSED_REALTIME flag instead of the RTC flag.

My guess is that the alarm manager is thinking it's missed a ton of alarms because you are using the RTC flag which means the alarm manager is expecting you to send a time value in milliseconds since Jan 1st 1970, but instead you are sending elapsed milliseconds since the device booted, which is going to be a much much smaller number.

If you use the RTC flags you need to use System.currentTimeMillis() or get the time in milliseconds from a Java Date or Calendar object. If you use ELAPSED_REALTIME flags then you need to use SystemClock.elapsedRealtime().

mbaird
Thanks for you comments mbaird.I may know why the device didn't go to sleep. The alarm sends broadcast too frequently (every 15 seconds), which kept the device awake.
mbaird, your comments about using System.currentTimeMillis() is correct. Thanks.