How to use Android AlarmManager with small intervals like 1 minute?

前端 未结 3 457
执念已碎
执念已碎 2020-12-18 07:09

I want to make some external service monitor and be notified on problems as fast as possible.

I tried to set up AlarmManager with 1-2 minutes interval,

3条回答
  •  遥遥无期
    2020-12-18 07:47

    Posting a code snippet that we have used.Please modify as per your requirement. We use it for every 15 seconds and it works.

    public class AlarmManagerBroadcastReceiver extends BroadcastReceiver  
    {
    private static final int _REFRESH_INTERVAL = 60 * 1; // 1 minutes
    // Alarm id
        private static final int ALARM_ID = 102; // This can be any random integer.
    
        PendingIntent pi = null;
        AlarmManager am= null;
    
    @Override
        public void onReceive(Context context, Intent intent) 
        {
            /* All actions to be handled here.. */
            }
    
    
        // This is to initialize the alarmmanager and the pending intent. It is done in separate method because, the same alarmmanager and
        // pending intent instance should be used for setting and cancelling the alarm.
    
        public void SetContext(Context context)
        {
            this.context = context;
            am=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
            pi = PendingIntent.getBroadcast(context, ALARM_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    
        // Setting the alarm to call onRecieve every _REFRESH_INTERVAL seconds
        public void SetAlarm()
        {
            // am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * _REFRESH_INTERVAL , pi);
            try
            {
                am.cancel(pi);
            }catch (Exception ignored){}
            am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), 1000 * _REFRESH_INTERVAL , pi);
        }
    
        // Cancel the alarm.
        public void CancelAlarm()
        {
            am.cancel(pi);
        }
    
    }
    

提交回复
热议问题