简体   繁体   中英

How to call some task once app is in resume status in every 15minutes

I want to perform an action on every 15 minutes once the device become sleep mode or app is in background. I tried it with broadcast Receiver as shown below. But it's only working for first few minutes. After that the action is not happening.

BroadcastReceiver

public class KeepReceiver extends BroadcastReceiver 
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
      Log.d("Keep","status");
        context.sendBroadcast(new Intent("KEEP_RECEIVER"));
       
    }
}

sendBroadcast be like below.:

 BroadcastReceiver broadcastReceiver2 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            
                    Log.d("Active","status");
                 
                }
            });
    

Here onReceive from KeepReceiver is called but sendBroadcast onReceive is not working after few minutes.

Methid called on onPause of main activity

private void timeout() {

        Date when = new Date(System.currentTimeMillis());
        Calendar now = Calendar.getInstance();
        now.set(Calendar.MINUTE, 0);
        now.set(Calendar.SECOND, 0);
        now.set(Calendar.MILLISECOND, 0);
        try {
            Intent someIntent = new Intent(getApplicationContext(), KeepReceiver.class); 

            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),0, someIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            int repeatingInterval = 100000; 

            AlarmManager alarmManager =(AlarmManager)getApplicationContext().getSystemService(Activity.ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), repeatingInterval , pendingIntent);


        } catch(Exception e) {
            e.printStackTrace();
        }
}

Please advise if anything wrong with the implementation. Thanks in advance

There are a few problems here. You cannot reliably set a repeating alarm at 100 second (less than 2 minute) intervals, as you are trying to do. Repeating alarms are also not accurate as Android can delay them to avoid battery drain.

To achieve a repeating alarm with 15 minute intervals, you should set a single alarm using set() or setExact() (if you need exact timing) for a time 15 minutes in the future. When that alarm goes off, do whatever you need to do and then set another alarm for 15 minutes in the future, etc.

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