private void one() { handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case 123: tv.setText(""+msg.obj); break; } } }; new Thread(){ @Override public void run() { super.run(); for (int i=0;i<3;i++){ try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Message message=new Message(); message.what=123; message.obj="通过Handler机制"; handler.sendMessage(message); } }.run(); }2,runOnUiThread方法用Activity对象的runOnUiThread方法更新,在子线程中通过runOnUiThread()方法更新UI,强烈推荐使用。
private void two(){ new Thread(){ @Override public void run() { super.run(); for (int i=0;i<3;i++){ try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } runOnUiThread(new Runnable() { @Override public void run() { tv.setText("通过runOnUiThread方法"); } }); } }.run(); }3,View.post(Runnable r)这种方法更简单,但需要传递要更新的View过去,推荐使用private void three(){ new Thread(){ @Override public void run() { super.run(); for (int i=0;i<3;i++){ try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } tv.post(new Runnable() { @Override public void run() { tv.setText("通过View.post(Runnable r) 方法"); } }); } }.run(); }4,AsyncTaskprivate void four(){ new MyAsyncTask().execute("通过AsyncTask方法"); }private class MyAsyncTask extends AsyncTask{ @Override protected Object doInBackground(Object[] objects) { for (int i=0;i<3;i++){ try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } return objects[0].toString(); } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); tv.setText(o.toString()); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)