警报创建后立即 运行

Alarm is running immediately after it is created

我正尝试在每天晚上 7 点播放铃声,但它在其挂起的意图正在注册广播后立即播放铃声。

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

@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 中接收这个广播时播放铃声 class Data Processor 的 on Receive 方法 class:

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


    playRIng(ctx);

 }

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

为什么不使用条件?:

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

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

 }

如果您在晚上 9 点 运行 该代码,您将告诉 AlarmManager 意图应该是 运行 2 小时前的第一次。

您需要检查日历时间是否晚于当前时间。
如果是,您需要在日历中添加一天,以便明天晚上 7 点首先触发。

类似这样的方法可能有效:

    c = Calendar.getInstance();
    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    int interval = 1000 * 60 * 60 * 24;
    // Not needed
    // c.setTimeInMillis(System.currentTimeMillis());
    c.set(Calendar.HOUR, 19);
    c.set(Calendar.MINUTE, 00);

    // ** Add this **
    // Check if the Calendar 7pm is in the past
    if (c.getTimeInMillis() < System.currentTimeMillis())
        c.add(Calendar.DAY_OF_YEAR, 1); // It is so tell it to run tomorrow instead

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

您可以尝试开发者网站上的示例,了解可用的示例代码 there.May 如果您的代码中存在一些编程错误,但那里可用的示例代码完全符合您的要求。

Scheduling Repeating Alarms

最好的方法,玩弄小时和分钟。

注意:请检查您的时间伴侣。就我而言,它是 24 小时甲酸盐

示例:

     Calendar c = Calendar.getInstance();
   //for 12 hr formate user int hour = c.get(Calendar.HOUR);
    int hour = c.get(Calendar.HOUR_OF_DAY);
    int minute = c.get(Calendar.MINUTE);
    //Log.e("time",""+hour+":"+minute);

    if (hour == 10 && minute == 0 ) {

     }