if you want to doing thread and display UI, below sample code will make you display and update the UI at the thread mode.
package com.powenko.Tutorial_thread_HandlerAndRun; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; public class Tutorial_thread_HandlerAndRunActivity extends Activity { protected ProgressDialog autoProgressDialog3; protected Handler handler; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Fun_hread_HandlerAndRun(); Fun_hread_HandlerAndRun_Delay(); } protected void Fun_hread_HandlerAndRun(){ ///////////////////////////////// handler=new Handler(); try{ if(autoProgressDialog3!=null){ autoProgressDialog3.dismiss(); autoProgressDialog3=null;} autoProgressDialog3 = ProgressDialog.show(this, "", "waiting...", true); new Thread(new Runnable() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { Fun_DoSomething(); if(autoProgressDialog3!=null){ autoProgressDialog3.dismiss(); autoProgressDialog3=null;} } }); } }).start(); } catch(Exception e){ } } //////// protected void Fun_hread_HandlerAndRun_Delay(){ ///////////////////////////////// handler=new Handler(); try{ if(autoProgressDialog3!=null){ autoProgressDialog3.dismiss(); autoProgressDialog3=null;} autoProgressDialog3 = ProgressDialog.show(this, "", "waiting...", true); new Thread(new Runnable() { @Override public void run() { handler.postDelayed(new Runnable() { @Override public void run() { Fun_DoSomething(); if(autoProgressDialog3!=null){ autoProgressDialog3.dismiss(); autoProgressDialog3=null;} } },100); } }).start(); } catch(Exception e){ } } protected void Fun_DoSomething(){ try{ SystemClock.sleep(2000); } catch(Exception e){ } } }
if you don’t want to display waiting dialog,
below code could make it working,
The simple fix to your example is:
final Runnable r = new Runnable() { public void run() { tv.append("Hello World"); handler.postDelayed(this, 1000); } }; handler.postDelayed(r, 1000);
Or we can use normal thread for example (with original Runner):
Thread thread = new Thread() { @Override public void run() { try { while(true) { sleep(1000); handler.post(r); } } catch (InterruptedException e) { e.printStackTrace(); } } }; thread.start();
sample code:
Tutorial_thread_HandlerAndRun