1

I am using broadcastreceiver to update the Activity every minute, however, I want to change it to every 2 minutes. How can I achieve that?

Below is the code for my function -

private void startMinuteUpdated() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK);

        minuteUpdateReceiver= new BroadcastReceiver() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onReceive(Context context, Intent intent) {
                lastUpdatedTimeTextDeparture.setText(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm")));
            }
    };
        registerReceiver(minuteUpdateReceiver, intentFilter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startMinuteUpdated();

    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(minuteUpdateReceiver);
    }
  • you can also use alarm manager for that, and can set repeating alarm depending upon your interval, you can check this answer over here - https://stackoverflow.com/a/17099023/5353830 – Rai_Gaurav Feb 19 '21 at 13:49

1 Answers1

1

You can alter your current implementation to read the minutes from current time and if its remainder by 2 is 0 then do your stuff, or else return. Doing this will allow you to update when the minutes are in even value (i.e. running every second minute).

if (Calendar.getInstance().get(Calendar.MINUTE) % 2 != 0){
   // don't proceed further
   return;
}

// update the activity
waqaslam
  • 67,549
  • 16
  • 165
  • 178