Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does Handler::postDelay make UI frozen
    text
    copied!<p>I have this code. I don't know why postDelay make UI frozen in this case. I want the Runnable will run after 100 miliseconds deley and run in 4000 miliseconds.</p> <pre><code>package com.delaythread; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ProgressBar; public class MyNeedActivity extends Activity implements OnClickListener { private ProgressBar progressBar; private final Handler handler = new Handler() { @Override public void handleMessage(final Message msg) { super.handleMessage(msg); progressBar.setVisibility(ProgressBar.INVISIBLE); } }; @Override public void onClick(final View v) { if(v.getId() == R.id.button1) { /* This call doesn't make ProgressBar frozen. final Thread t = new Thread(new MyRunnable()); t.start(); progressBar.setVisibility(ProgressBar.VISIBLE); */ // This makes ProgressBar frozen in 4000 miliseconds. final boolean b = handler.postDelayed(new MyRunnable(), 100); if(b) { progressBar.setVisibility(ProgressBar.VISIBLE); } } } /** Called when the activity is first created. */ @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ((Button)findViewById(R.id.button1)).setOnClickListener(this); progressBar = (ProgressBar)findViewById(R.id.progressBar1); } private class MyRunnable implements Runnable { @Override public void run() { sleep(); } private void sleep() { try { Thread.sleep(4000); handler.sendEmptyMessage(0); } catch (final InterruptedException e) { e.printStackTrace(); } } } } </code></pre> <p><strong>Update</strong>: Actually what I want is AsyncTask executes after a delay time, so I do as this answer <a href="https://stackoverflow.com/questions/4177409/java-android-how-to-start-an-asynctask-after-3-seconds-of-delay">Java/android how to start an AsyncTask after 3 seconds of delay?</a>. He said I should use Handler and Runnable.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload