Skip to content Skip to sidebar Skip to footer

Fire Alarm Manager In Every 5 Min Android

i want to make a service which fire alarm manager in every 5 min interval when my application is running only..so how to do it? Intent intent = new Intent(this, OnetimeAlarmReceiv

Solution 1:

try this:

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5*60*1000, pendingIntent);

that alarm will be repeating forever until you cancel it, so you need to cancel it on getting the event when you no longer need it.

Solution 2:

privateclassProgressTimerTaskextendsTimerTask {
        @Overridepublicvoidrun() {
            runOnUiThread(newRunnable() {
                @Overridepublicvoidrun() {
                    // set your time hereintcurrenSeconds=0
                    fireAlarm(currenSeconds);
                }
            });
        }
    }

Inizialize :

TimerprogressTimer=newTimer();
     ProgressTimerTasktimeTask=newProgressTimerTask();
     progressTimer.scheduleAtFixedRate(timeTask, 0, 1000);

Solution 3:

Cancel the AlarmManager in onPause() of the activity.

A much better solution would be to use a Handler with postDelayed(Runnable r, 5000) since you said only when your application is running. Handlers are much more efficient than using AlarmManager for this.

Handler myHandler = newHandler();
Runnable myRunnable = newRunnable(){
   @Overridepublicvoidrun(){
      // code goes here
      myHandler.postDelayed(this, 5000);
   }
}

@OverridepublicvoidonCreate(Bundle icicle){
   super.onCreate(icicle);
   // code
   myHandler.postDelayed(myRunnable, 5000);
   // to start instantly can call myHandler.post(myRunnable); instead// more code
}

@OverridepublicvoidonPause(){
   super.onPause();
   // code
   myHandler.removeCallbacks(myRunnable); // cancels it// code
}

Solution 4:

Set Alarm repeating every 5 minutes in Kotlin

val intent = Intent(context, OnetimeAlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (1000 * 60 * 5).toLong(), pendingIntent)

To cancel Alarm

val intent = Intent(context, OnetimeAlarmReceiver::class.java)
        val sender = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        alarmManager.cancel(sender)

Post a Comment for "Fire Alarm Manager In Every 5 Min Android"