Search code examples
javaandroid-studioandroid-activity

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?


Solution

  • 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.

    1. https://www.geeksforgeeks.org/singleton-class-java/

      class Timer{
          private static Timer timer=null;
              public get_instance(){
              if(timer==null){
                 timer=new Timer();
              }
          return timer;
          }
      }
      
    2. Pass using intent

    //To pass:
        intent.putExtra("MyTimer", obj);
    
    // To retrieve object in second Activity
        getIntent().getSerializableExtra("MyTimer");
    
    1. using application activity

       import android.app.Application;
      
       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!
           @Override
           public void onCreate() {
               super.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!
           @Override
           public void onConfigurationChanged(Configuration newConfig) {
               super.onConfigurationChanged(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!
           @Override
           public void onLowMemory() {
               super.onLowMemory();
           }
       }