2016-12-06 130 views
-1

我有一个TimePicker和一个Button,我想设置一个警报,当用户在指定的时间点击ButtonBroadcastReceiver延迟触发

当我点击按钮时,它会获得小时,但有时会在特定时间触发闹钟,但并非总是如此。它在指定的时间内被激发的次数少于未被激发的次数。大多数BroadcastReceiver在指定的时间没有开火,它会延迟启动。

这是代码,我现在所拥有的:

在报警类(代码refered到广播接收器)

AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE); 
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class); 
PendingIntent alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0); 

Calendar cal= Calendar.getInstance(); 

cal.set(Calendar.MONTH,cal.get(Calendar.MONTH)); 
cal.set(Calendar.YEAR,cal.get(Calendar.YEAR)); 
cal.set(Calendar.DAY_OF_MONTH,cal.get(Calendar.DATE)); 
cal.set(Calendar.HOUR_OF_DAY,hour); 
cal.set(Calendar.MINUTE,minutes); 


alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000 * 60 * 5, alarmIntent); 

其中hourminutes是从TimePicker检索小时和分钟。

在AlarmReceiver类

public class AlarmReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Log.d("prove", "We enter on BroadcastReceiver"); 
    } 
} 

上的Manifest.xml

<receiver 
    android:name=".AlarmReceiver" 
    android:enabled="true" > 
</receiver> 

例如,我已经把日志,看看我是从TimePicker检索显示日志之前什么时候BroadcastReceiver。我点击它在16:48(在TimePicker),这是结果:

12-06 16:47:02.951 7980-7980/com.project.user.project D/prove: hour: 16:48 
12-06 16:50:23.727 7980-7980/com.project.user.project D/prove: We enter on BroadcastReceiver 
12-06 17:00:01.070 7980-7980/com.project.user.project D/prove: We enter on BroadcastReceiver 

正如你所看到的,BroadcastReceiver已经在16:5017:00发射两枚时候,我想他们应该开火16:4816:53因为我已经确定它们之间会延迟5分钟,而不是在这种情况下10分钟。

那么,我能做些什么来在准确的时间点火,而不是延迟点火呢?我是否缺少一些配置?

在此先感谢!

回答

1

如前所述in the documentationsetRepeating是不精确的。

从API 19开始,所有重复的警报都是不精确的。如果您的应用 需要精确的交货时间,那么它必须使用一次性精确警报,如上所述每次重新计划 。旧的应用程序,其 targetSdkVersion比API 19较早将继续拥有所有的 其警报,包括重复报警,如精确的处理

所以,火在准确的时间作为API 19的报警,使用setExact ,并在每个闹钟内设置下一个闹钟。

安排一个报警,在规定的时间准确发送。

+0

我有一个问题,如果我有一个报警,应该在确切的时间重复两到三次。例如,在'16:48','16:50'和'16:52'。我应该添加三个调用'setExact'函数的事件吗? –

+0

如果你想设置3组报警,他们没有特定的模式,那么我相信你应该使用'setExact'三次,是的。否则,如果您希望闹钟每2分钟触发一次(例如),则只需使用setExact一次并重新安排在接收器中,如上所述。 – MohanadMohie

+0

是的,他们将有一个特定的模式,例如,每2分钟。但是我不明白他们说'重新安排'的意思。 –

0

使用setInexactRepeating

alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), 1000 * 60 * 5, alarmIntent); 

你可以检查我的代码我在我的app.I做的工作完美。

pendingIntent = PendingIntent.getBroadcast(this, _id, myIntent, PendingIntent.FLAG_CANCEL_CURRENT); 

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, timeToAlarm, AlarmManager.INTERVAL_DAY, pendingIntent); 

愿它帮助..

+0

如果任何其他查询超过请告诉 – Kush

+0

但我需要在指定的时间精确的报警。并且在文档https://developer.android.com/reference/android/app/AlarmManager.html#setInexactRepeating(int,long,long,android.app.PendingIntent)中说明了以下内容:'安排一个不精确的重复警报触发时间要求;例如,每小时重复一次,但不一定每小时重复一次。“ –

+0

检查我的代码.. – Kush