1

I am trying to automatically start a simple timer when the activity shows up. Currently, the activity will not load visibly until my operation is done. Should I override another method?

@Override
protected void onStart() {
    super.onStart();
    for (int i = 0; i <= 100; i++) {
        ((TextView) findViewById(R.id.timer)).setText(String.valueOf(i));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            Log.e("timer", e.getMessage());
        }
    }
}
Rb87
  • 180
  • 1
  • 9

3 Answers3

2

You are blocking main thread, use Handler with Runnable instead

handler = new Handler();

final Runnable r = new Runnable() {
    public void run() {
        tv.append("Hello World");
        handler.postDelayed(this, 1000);
    }
};

handler.postDelayed(r, 1000);
Maksym V.
  • 2,877
  • 17
  • 27
  • Does this cause the Runnable to possibly modify the TextView off the UI thread, and if so, is that going to be okay? – Yonatan Oct 22 '18 at 05:56
  • well it is not the best option, I would use MutableLiveData and databinding. In that way you will postValue which is thread safe. – Maksym V. Oct 22 '18 at 05:59
  • I understand that the issue is the main thread been blocked. How ever i am still interested for general knowledge to find out if there is another method that is called when the graphics are already been loaded and visible. – Rb87 Oct 23 '18 at 00:54
1

Pausing the current thread in order to create a timer is a really bad idea.CheckOut Timer class and have a look at scheduleAtFixedRate() method in that class and extract ((TextView) findViewById(R.id.timer)) out from for loop.

have a look at How to set a Timer in Java?

m3g4tr0n
  • 591
  • 7
  • 15
1

While activity running in onStart(),you may see part of your layout ,not all of your layout. Maybe you can override method onWindowFocusChanged(),and then start a Thread. And why you use 'super.onResume()' in onStart()? I don't understand:)

  • Yeah, it's a copy paste mistake – Rb87 Oct 23 '18 at 01:01
  • But would onWindowFocusChanged() be called on different events? for instance screen orientation change? – Rb87 Oct 23 '18 at 01:03
  • 1
    All of the Window focus changed ,it will be called,include screen orientation change.The screen orientation change will destory current activity and reCreate it.Sometimes you must save the Activity state. – Seraph Gabriel Oct 23 '18 at 01:24