androidandroid-activitythread-sleepactivity-lifecycleonstart

Activity onStart() operation results in a blank screen


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());
        }
    }
}

Solution

  • 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);