Java – How to Access Handler/Runnable Class from All Other Classes in Android

androidjavaobject-oriented

I am trying to create a class which allows me to do something every 5 seconds and I want to be able to start and stop this from running from any of the other classes. Here is my Timer class:

public class Timer extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);


}

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {

        public void run() {

            Toast.makeText(getApplicationContext(), "DISPLAY MESSAGE", Toast.LENGTH_SHORT).show();
            handler.postDelayed(runnable, 5000);
        }
    };
}

Now my knowledge on Object Orientated programming is not as good as I thought it was, I am used to creating instances of classes and using the classes properties, but how can I use a classes properties once across the whole program, do I still create instances of the Timer class in other classes? Should I use the Singleton pattern, or should I make the class static?

So basically In Class1 I would like to start the timer by doing this:

Timer.runnable.run();

And perhaps in Class2 stop the runnable started in Class1 by doing this:

Timer.handler.removeCallbacks(runnable);

I am looking for advice and an explanation on the correct way to program this idea and why.

Thank you!

Related Topic