How to call onClick method every x hour or minutes? [Android]

Viewed 40

I'm beginner. In my application I have a button which get a stats from class to MainActivity and set text on textview. In method onClick are other methods call too. Everything works fine, I can click the button manually and get all information, but I want to add automatic call onClick method for example in every 1 hour. I read about AlarmManager and Timer to do that, but I don't know how to implement it in my case.

Below code with method onClick. It's on MainActivity in OnCreate.

statsBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            UStats.printCurrentUsageStatus(MainActivity2.this);

            long time = UStats.printCurrentUsageStatus(MainActivity2.this);

            if (time >= 300000)
            {
                sendOnChannel1();
            }

            String total="";
            long sec=time/1000;
            long day;
            long hour;
            long min;
            if(sec>=(86400)){
                day=sec/86400;
                sec=sec%86400;
                total=total+day+"d ";
            }
            if(sec>=3600){
                hour=sec/3600;
                sec=sec%3600;
                total=total+hour+"h ";
            }
            if(sec>=60){
                min=sec/60;
                sec=sec%60;
                total=total+min+"min ";
            }
            if(sec>0)
            {
                total=total+sec+"s";
            }
            facebook_time.setText(String.valueOf(total));

            saveData();

        }

    });

Or how to create method which will be do the same as button, and then this method will be call every hour? I just want to update textview automatic every some time.

1 Answers

You can use a handler and a runnable. Try these steps:

  1. Create 3 variables in your class of Runnable, int and Handler like this:
private Runnable mRunnable;
private Handler mHandler;
private int seconds = 5; // this is the seconds of how much time the click listener with be called
  1. Initialise it in the onCreate() something like this:
mRunnable = () -> {
   yourButton.onClick();
   mHandler.postDelayed(mRunnable, seconds * 1000);
}

mHandler = new Handler();
  1. You need to also start the handler. So, use this to start it. I'd prefer to use this in onCreate():
mHandler.postDelayed(mRunnable, seconds * 1000);
Related