“警报管理器集重复”;在1分钟内没有重复? [英] "Alarm Manager Set repeating" is not repeating under 1 minute?

查看:88
本文介绍了“警报管理器集重复”;在1分钟内没有重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用警报管理器设置后台服务。

I am trying to set a background service with alarm manager.

  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秒)为什么会发生提示?

But it is not working every 15 seconds. Sometimes works after 20 seconds, sometimes after 1 minute. But, When I set 1 minute(60*1000)it is not also the exact time. it's close.(1 minute 4 second, 1 minute 13 second) Why is that happing?

推荐答案

默认情况下,重复警报是不精确的自API 19起。

Repeating alarms are by default inexact since API 19.

一种解决方法是在x秒内设置一个简单的准确警报,然后在触发警报时递归设置另一个警报。这段代码对我来说就像一个魅力。您所需要做的就是在XML中定义服务:

A workaround is to set a simple exact alarm in x seconds and then set another alarm recursively when the alarm is triggered. This code works for me like a charm. All you need to do in addition is define the service in your XML:

<receiver android:name=".AlarmReceiver" android:process=":remote" />

在主要活动中,您可以这样开始:

From the main activity you start it like this:

AlarmReceiver alarm = new AlarmReceiver();
alarm.setAlarm(this);

安排警报的服务与接收警报的服务相同:

The service in which you schedule the alarm is the same in which it is also received:

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
    }
}

这篇关于“警报管理器集重复”;在1分钟内没有重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆