笔记:
// 使用handler.post(Runnable)更新UI public void updateUI_Fun1() { new Thread() { public void run() { Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { textView.setText("this is update content"); } }); }; }.start(); } // 使用handler发送消息更新UI public void updateUI_Fun2() { Handler handler = new Handler(new Callback() { @Override public boolean handleMessage(Message msg) { // 对handler发送消息的预处理,返回falst则执行下面的handlerMessage() true则不执行 return false; } }) { public void handleMessage(Message msg) { textView.setText("this is update content"); }; }; } // 使用UI线程更新UI public void updataUI_Fun3() { runOnUiThread(new Runnable() { @Override public void run() { textView.setText("updata ui content"); } }); } // 使用View.post( Runnable)更新UI public void updateUI_Fun4() { textView.post(new Runnable() { @Override public void run() { textView.setText("this is update context"); } }); }
使用子线程自带的Looper更新UI:
代码笔记:
private Handler handler2; private HandlerThread thread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); myHandlerThread = (Button) findViewById(R.id.MyThreadHandler); handlerThread = (Button) findViewById(R.id.HandlerThread); //利用HandlerThread线程执行耗时操作,可以简单代替AsyncTask等。主线程给子线程发送消息 handlerThread.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { thread=new HandlerThread("aaaa"); thread.start(); handler2=new Handler(thread.getLooper()){ @Override public void handleMessage(Message msg) { Toast.makeText(SecondActivity.this, "this is HandlerThread", Toast.LENGTH_SHORT).show(); } }; handler2.sendEmptyMessage(1); } });