我正在尝试使用警报管理器设置后台服务。
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pending);
//alarmManager.SetExact(AlarmType.RtcWakeup, SystemClock.ElapsedRealtime() + 5 * 1000, pendingIntent);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime()+15*1000 , 15*1000, pending);
但它并不是每 15 秒就工作一次。有时20秒后起作用,有时1分钟后起作用。但是,当我设置 1 分钟(60*1000)时,它也不是准确的时间。很接近了。(1分4秒,1分13秒)为什么会这样?
最佳答案
自 API 19 起,重复警报默认不精确。
解决方法是在 x 秒内设置一个简单的精确警报,然后在触发警报时递归设置另一个警报。这段代码对我来说就像一个魅力。您只需在 XML 中定义服务即可:
<receiver android:name=".AlarmReceiver" android:process=":remote" />
从主要 Activity 开始,如下所示:
AlarmReceiver alarm = new AlarmReceiver();
alarm.setAlarm(this);
您安排警报的服务与接收警报的服务相同:
public class AlarmReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
setAlarm(context);
//Put whatever you want to do below here
}
public void setAlarm(Context context)
{
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis()/1000L + 5L) *1000L, pi); //Next alarm in 5s
}
}
关于java - "Alarm Manager Set repeating"在 1 分钟内没有重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59425417/