Search code examples
javaandroidbroadcastreceiver

How to update activity every 2 minutes using broadcast receiver in Android?


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);
    }

Solution

  • 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