Summary of several ways for android to refresh the UI, and several ways for android to refresh the ui
First, the UI refresh of android is completed in the main thread (UI thread. Among the four components, activity and service run in the main thread. Now we will summarize the UI refresh methods that we often use in projects.
First, use the subthread to send messages to refresh the UI.
The sub-thread is responsible for processing the data required by the UI, and then sending messages to the main thread to refresh the UI. The code structure is as follows:
new Thread(new Runnable() {@Overridepublic void run() {Person person=new Person();person.setName(mName.getText().toString().trim());person.setPhone(mPhone.getText().toString().trim());Log.i("person",person.toString());DatabaseInfoFactory.getPersonDao(mContext).addPerson(person);Looper.prepare();Message msg=Message.obtain();msg.what=0x123456;handler.sendMessage(msg);Looper.loop();}}).start();
Main thread:
private Handler mHandler=new Handler(){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);if(msg.what==0x123456||msg.what==0x123){fillData();setListener();}}};
Second, use an asynchronous task to update the UI.The code structure is as follows:
New AsyncTask <Void, Void, Void> () {@ Overrideprotected void onPostExecute (Void result) {if (mAdapter = null) {mAdapter = new LeaveInfoAdapter (); // set the data adapter mLVleaveInfos. setAdapter (mAdapter); Log. I ("test", "Retrieving Database Data in the background of asynchronous task display");} else {mAdapter. yydatasetchanged ();} super. onPostExecute (result) ;}@ Overrideprotected Void doInBackground (Void... params) {// obtain the data to be displayed mleaveInfos = mLeaveInfosDao. findAll (); if (mleaveInfos = n Ull) {Toast. makeText (HomeActivity. this, "the leave data does not exist or has been cleared! ", 500). show ();} Log. I (" test "," obtain database data in the asynchronous task background "+ mleaveInfos. size (); return null1_0000.exe cute ();
Third, use the configuration file + activity lifecycle method to refresh the UI.