Java – How Android executes a method every x hours or minutes

How Android executes a method every x hours or minutes… here is a solution to the problem.

How Android executes a method every x hours or minutes

I’m trying to run a method called Updater() with the alert service, and for testing purposes I want it to update every 1 minute and eventually every 2 hours. If the toggle button is on, the scheduled task executes itself on the timer and stops the timer when the toggle button is off
So far, here’s my code. Can someone tell me what I’m doing wrong?

 public class AlarmReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) {
        Updater();
    }
}
public void autoUpdateClick(View view)
{
    AlarmManager alarmManager=(AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this,AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    boolean on = ((ToggleButton) view).isChecked();
    if (on)
    {
      alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),30000,pendingIntent);
        Toast.makeText(getBaseContext(),"Check-In will be done every 2 hours",Toast.LENGTH_SHORT).show();
    }
    else
    {
     alarmManager.cancel(pendingIntent);
        Toast.makeText(getBaseContext(),"Manual Check-In enabled",Toast.LENGTH_SHORT).show();
    }

}

Related Problems and Solutions