Global Timer in android

后端 未结 5 856
日久生厌
日久生厌 2021-01-21 13:40

I want to make a timer which will be shown on every activity of my application.

I know how to make a timer on an activity below is my code

public class T         


        
5条回答
  •  清歌不尽
    2021-01-21 14:15

    You can have a singleton class holding your CountDownTimer

    // This is not a real singleton, Google to get a proper Java implementation
    public class TimerSingleton {
    
      // Should not be public, you should of course encapsulate access to that timer.
      // static keyword says that one timer object is shared by all instance of TimerSingleton 
      public static CountDownTimer timer = new CountDownTimer();
    }
    
    // Access to the timer from an activity:
    TimerSingleton.timer.start();
    

    Second option is to have your timer as a member of a custom Application class: Use Application class for global variables

    Third option : make a local service that starts the timer when started.

    Keep in mind that in case of options 1 and 2, if the OS decides to kill you app, the timer will vanish (i.e. when the activity is re-created, the CountDownTimer object will be resetted).

提交回复
热议问题