当前位置: 首页 > 科技观察

Android异步更新UI的四种方式

时间:2023-03-13 07:56:46 科技观察

大家都知道,由于性能要求,android要求只能在UI线程中更新UI。如果想在其他线程更新UI,我大致总结了4种方式。欢迎补充指正:使用Handler消息传递机制;使用AsyncTask异步任务;使用runOnUiThread(action)方法;使用Handler的post(Runnabelr)方法;以下四种方法用于更新TextView。1.使用Handler消息传递机制packagecom.example.runonuithreadtest;importandroid.app.Activity;importandroid.os.Bundle;importandroid.os.Handler;importandroid.widget.TextView;publicclassMainActivityextendsActivity{privateTextViewtv;Handlerhandler=newHandler(){publicvoidhandleMessage(.os.Messagemsg){if(msg.what==0x123){tv.setText("UpdatedTextView");}};};@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv=(TextView)findViewById(R.id.tv);newMyThread().start();}classMyThreadextendsThread{@Overridepublicvoidrun(){//延迟更新两秒try{Thread.sleep(2000);}catch(InterruptedExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}handler.sendEmptyMessage(0x123);}}}2.使用AsyncTask异步任务注意:更新UI的操作只能在onPostExecute(String结果)方法。packagecom.example.runonuithreadtest;importandroid.app.Activity;importandroid.os.AsyncTask;importandroid.os.Bundle;importandroid.widget.TextView;publicclassMainActivityextendsActivity{privateTextViewtv;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv=(TextView)findViewById(R.id.tv);newYibu().execute();}classYibuextendsAsyncTask{@OverrideprotectedStringdoInBackground(String...params){try{Thread.sleep(2000);}catch(InterruptedExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}returnnull;}@OverrideprotectedvoidonPostExecute(Stringresult){//TODOAuto-generatedmethodstubtv.setText("更新后的TextView");}}}3。使用runOnUiThread(action)方法packagecom.example.runonuithreadtest;importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.TextView;publicclassMainActivityextendsActivity{privateTextViewtv;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv=(TextView)findViewById(R.id.tv);newMyThread().start();}classMyThreadextendsThread{@Overridepublicvoidrun(){runOnUiThread(newRunnable(){@Overridepublicvoidrun(){//TODOAuto-generatedmethodstubtry{//延迟两秒更新Thread.sleep(2000);}catch(InterruptedExceptione){e.printStackTrace();}tv.setText("更新后的TextView");}});}}}4.使用Handler的post(Runnabelr)方packagecom.example.runonuithreadtest;importandroid.app.Activity;importandroid.os.Bundle;importandroid.os.Handler;importandroid.widget.TextView;publicclassMainActivityextendsActivity{privateTextViewtv;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv=(TextView)findViewById(R.id.tv);Handlerhandler=newHandler();handler.post(newRunnable(){@Overridepublicvoidrun(){try{//延迟两秒更新Thread.sleep(2000);}catch(InterruptedExceptione){e.printStackTrace();}tv.setText("更新的TextView");}});}}

最新推荐
猜你喜欢