简体   繁体   中英

alarm manager not working while updating interval time

after reading all the QA i didnt get any proper solution. I have 2 problems
1. Alarm fires twice even if i register my receiver only in manifest.(not by code)
2. when i update interval time of alarm it gets fires randomly

here is my method for set alarm

 public void AlarmCall(int min) {

    Intent intent = new Intent(context, AlarmReceiver.class);
    PendingIntent pintent = PendingIntent.getBroadcast(context,0 , intent, 0);
    alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    cancelAlarm(alarm,pintent);
    if(Build.VERSION.SDK_INT<18) {
        alarm.set(AlarmManager.RTC_WAKEUP, 1000 * 60 * min, pintent);
    }
    else if(Build.VERSION.SDK_INT>=19 && Build.VERSION.SDK_INT<=22)
    {            alarm.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), 1000*60*min, pintent);
    }
    else if(Build.VERSION.SDK_INT>=23)
    {         alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,1000*60*min,pintent);
    }
}

method to cancel alarm :

public void cancelAlarm(AlarmManager alarm,PendingIntent p)
{
    alarm.cancel(p);
    Log.d("Alarm","Alarm Cancle");
}

in my project Application class i have to start alarm with 10 min time interval and it works fine , according to user input value i need to update time interval.
so i call this method with int min input value and cancel first alarm.
but in marshmallow it fires at every 5 seconds, and kitkat lollipop it fires randmoly.
even checked with setExact() method

I had the same issue, use setWindow solved the problem

long repeatInterval = 1000 * 60 * min;
long triggerTime = SystemClock.elapsedRealtime()
                    + repeatInterval;

AlarmManager alarms = (AlarmManager) this.getSystemService(
                    Context.ALARM_SERVICE);

if (Build.VERSION.SDK_INT >= 19) 
{
          alarms.setWindow(AlarmManager.RTC_WAKEUP, 
                     triggerTime, 
                     repeatInterval,
                     pendingIntent);
}else{
          alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                    triggerTime,
                    repeatInterval,
                    pendingIntent);}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM