AlarmManager.RTC不工作?

时间:2010-03-03 00:56:51

标签: android

我在ApiDemo中稍微改变了一下AlarmController.java,所以我希望在手机休眠时使用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);

接收者代码如下:

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();
    }
}

我运行了修改后的应用程序,但在手机进入睡眠状态后屏幕仍为黑色时,我仍然看到如下的许多日志消息:

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

这意味着AlarmManager.RTC标志不起作用。有人可以告诉我为什么吗?

感谢。

1 个答案:

答案 0 :(得分:8)

由于您使用elapsedRealtime来获取警报开始时间,我认为您需要使用ELAPSED_REALTIME标志而不是RTC标志。

我的猜测是,警报管理器认为它丢失了大量警报,因为您正在使用RTC标志,这意味着警报管理器期望您自1970年1月1日以来以毫秒为单位发送时间值,而不是您要发送自设备启动以来经过的毫秒数,这将是一个小得多的数字。

如果使用RTC标记,则需要使用System.currentTimeMillis()或从Java Date或Calendar对象获取以毫秒为单位的时间。如果使用ELAPSED_REALTIME标志,则需要使用SystemClock.elapsedRealtime()。