Search code examples
javaandroidtimervisibilitychronometer

Setting Chronometer to gone visibility stops it from working


I have this code, which calls a function every second. The function perfroms numerous tasks related to the progress of a speed test.

As you can see there is a line where the visibility is set to "gone". In Android 8.1.0 this causes the Chronometer to fail. The function onTimer() never gets called. In 7.1.1 this code works and the test runs as expected.

I need to keep the timer mechanism but I don't want to have the timer in view.

What are my options?

   public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            setContentView(R.layout.test);

            // 1 second timer
            Timer = (Chronometer)findViewById(R.id.Chronometer01);
            Timer.setVisibility(Chronometer.GONE);

            Timer.setOnChronometerTickListener(new OnChronometerTickListener()
            {
                @Override
                public void onChronometerTick(Chronometer arg0) 
                {
                    OnTimer();
                };
            });
            Timer.start();
        }

Solution

  • A Chronometer isn't usually something you'd use to perform background tasks (By doing so, you're relying on something in the presentation layer to perform business logic!). There are plenty of different ways of performing background tasks every n seconds without using UI objects, a fairly well accepted way is by using a Handler, which can repeatedly run a task contained in a Runnable every n milliesconds, like so:

    Handler handler = new Handler();
    
    private Runnable runnable = new Runnable () {
        @Override
        public void run() {
            OnTimer(); // Run your code
            handler.postDelayed(this, 1000); // re-run this Runnable object in 1 second
       }  
    }
    
    handler.post(runnable); // run the Runnable object now