user3788866
user3788866

Reputation: 118

How to run a function all the time continuously until the activity is in foreground?

I am having a function in my code.And I want this function to run after every 2 minute if the activity is in the foreground and stop it when it is in the background. Suppose I have a function x() just toasting "Hello World". I want to run this function after every two minute.

Upvotes: 1

Views: 3006

Answers (1)

M D
M D

Reputation: 47817

Make handler like

           Runnable r2=new Runnable() {
                @Override
                public void run() {
                    //Your Toast
                h2.postDelayed(r2,20000);   
                }
            };

            Handler h2=new Handler();

Call this handler in activity onResume()

h2.postDelayed(r2,20000);

and stop handler in activity onPause()

h2.removeCallbacks(r2);

Upvotes: 2

Related Questions