android - 警报在创建后立即运行

标签 android alarmmanager

我正尝试在每天晚上 7 点播放铃声,但它在其未决 Intent 注册广播后立即播放铃声。

我在单击按钮时在前台调用了该服务,并在 onStartCommand 中创建了挂起的 Intent :

@Override
public int onStartCommand(Intent intent, int flags, int startId) 
{

    startForeground(FOREGROUND_ID,
            buildForegroundNotification("DummyApp"));

    c = Calendar.getInstance();
    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    int interval = 1000 * 60 * 60*24;
    c.setTimeInMillis(System.currentTimeMillis());
    c.set(Calendar.HOUR, 19);
    c.set(Calendar.MINUTE,00);
    manager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),
            interval, pendingIntent);
    Intent alarmIntent = new Intent(AlarmService.this, DataProcessor.class);
    pendingIntent = PendingIntent.getBroadcast(AlarmService.this, 0,
            alarmIntent, 0);
    return START_STICKY;
}

现在我在 DataProcessor 类的 Data Processor 类的 Receive 方法中收到这个广播时播放铃声:

@Override
public void onReceive(Context ctx,Intent intent) {


    playRIng(ctx);

 }

但是当我运行此代码时,单击按钮,创建服务但在调用 AlarmService 并播放铃声后立即触发警报。这是怎么可能的,因为我在注册广播时给出了准确的 7 点钟时间.? 谷歌了很多,但只找到相同的代码,没有别的。每个代码都能在时间播放铃声,但在注册广播后也会立即播放铃声。

最佳答案

为什么不使用条件?:

@Override
public void onReceive(Context ctx,Intent intent) {
Calendar c = Calendar.getInstance(); 
 int hour = c.get(Calendar.HOUR);

if(hour==19) 
 {
    playRIng(ctx);
 }

 }

关于android - 警报在创建后立即运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29703113/

相关文章:

android - 警报管理器从未在 android 中触发

安卓 7.1.2 + ARMv7

android - 如何通过Gradle排除/删除 flavor 特定的 Assets 文件?

android - 从锁定屏幕开始 Activity 时无声音

android - 首次运行 Android 应用程序时运行代码

当应用程序处于打瞌睡模式时,由警报管理器触发的 Android 通知不会触发

java - 安卓 : Json Parsing show error

android - 我可以从 Flutter 导出我的 sqlite 数据库吗?

android - 在页面底部添加一个不重叠内容的 Admob 横幅

android - 在特定时间重新启动 Activity