How do I call a method only once in \`onCreate()\` and keep running it when changing activities


So I have an app that tells you after 4 hours of driving have passed that you should rest. When the user goes on another activity (let’s say the settings tab) and comes back to the main activity, that timer starts over again from 0. How do I stop that?


There would be a handful of ways you can address the issue.

First, you can create a singleton class. that operates the timer. This way it does not die. Second, you can pass the object in the intent Third, you can run the timer out of the application class rather then an activity.


    class Timer{
        private static Timer timernull;
            public get_instance(){
               timernew Timer();
        return timer;
  2. Pass using intent

    //To pass:
    intent.putExtra(“MyTimer”, obj);

    // To retrieve object in second Activity

  3. using application activity

     public class MyCustomApplication extends Application {
         // Called when the application is starting, before any other application objects have been created.
         // Overriding this method is totally optional!
         public void onCreate() {
             startTimer(); // This might be a better place for it
             // Required initialization logic here!
     // Called by the system when the device configuration changes while your component is running.
     // Overriding this method is totally optional!
     public void onConfigurationChanged(Configuration newConfig) {
     // This is called when the overall system is running low on memory, 
     // and would like actively running processes to tighten their belts.
     // Overriding this method is totally optional!
     public void onLowMemory() {


Answered By – Drivers Sea

Leave a Comment