我正尝试在每天晚上 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/