androidglobal-variableschronometer

How to build a global timer that appears in all app screens


I want to build a global timer with a value increments and appear across all app activities using Chronometer ,how to make the Chronometer value global to all app?


Solution

  • Entire code solution but basic idea i can give you and this is how i implemented.

    In BaseActivity or in Application class you can take the static timer in my case i have taken in BasActivity.

    public static CountDownTimer timerBase;
    private long startTimer;
    

    Now on particular action this is how you can start the timer.

        public void sessionStart() {
    
            if (timerBase != null)
                timerBase.cancel();
              start = SystemClock.elapsedRealtime();
            timerBase = new CountDownTimer("Pass Total time the task should be excute", 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
    
                    long time = ("Pass Total time the task should be excute"/ 1000 - Math.round((float) millisUntilFinished / 1000.0f));
                    String timeTakenForeachQue = String.valueOf(time);
                    Log.e("counterValue", timeTakenForeachQue + " start = " + (SystemClock.elapsedRealtime() - start) / 1000 + " time " + millisUntilFinished / 1000);
    
                }
    
                @Override
                public void onFinish() {
                   // Do stuff when time finish
    
                    Toast.makeText(BaseActivity.this,"time finished" Toast.LENGTH_LONG).show();
    
                }
            }.start();
        }
    
    }
    

    Now you can access this method in any class as it is BaseActivity or in Application class.Also this is just basic idea how to implement as entire task not possible to publish.