Android Async Thread Update UI

Source: Internet
Author: User

Async with new UI:

1, Handler+thread (runnable): If handler and Thread are written in a Java file, do not say, if the runnable is defined in a separate class file, you can receive the handler parameter in the constructor method, Then after the time-consuming operation, send a message via handler to notify the main UI thread to update the UI

2, interface callback, define an interface, and then in the main UI time-consuming operation, with the help of anonymous inner class, where the asynchronous thread returned to the data processing operations, the asynchronous thread receives an anonymous internal class instance, and then after the time-consuming operation to callback the interface method, You can return the results of a time-consuming operation to a callback function

1 of the Code implementation:

 Packagecom.example.testtesttest;ImportOrg.json.JSONArray;ImportCom.example.testtesttest.DataRunnable.dataCallBackLisener;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;Importandroid.app.Activity;Importandroid.app.FragmentTransaction;ImportAndroid.content.DialogInterface;ImportAndroid.content.DialogInterface.OnClickListener;ImportAndroid.support.v4.app.FragmentManager;ImportAndroid.util.Log;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.widget.Button; Public classMainactivityextendsActivityImplementsandroid.view.view.onclicklistener{PrivateButton Button =NULL; PrivateDatacallbacklisener Callbacklistener; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);            Setcontentview (R.layout.activity_main); Button=(Button) Findviewbyid (R.id.button); Button.setonclicklistener ( This); } @Override Public voidOnClick (View v) {Switch(V.getid ()) { Caser.id.button:datarunnable runnable=Newdatarunnable (handler); Thread Thread=NewThread (runnable);                            Thread.Start ();  Break; default:         Break; }        }                 PublicHandler Handler =NewHandler () { Public voidhandlemessage (android.os.Message msg) {Switch(msg.what) { Case1: Button.settext ("HHH");  Break; default:                     Break;        }            };                }; }
 Packagecom.example.testtesttest;ImportAndroid.os.Handler; Public classDatarunnableImplementsrunnable{Privatestring[] Datastring =NewString[5]; PrivateDatacallbacklisener Listener; PrivateHandler DataHandler;  Publicdatarunnable (Datacallbacklisener alistener) { This. Listener =Alistener; }     Publicdatarunnable (Handler ahandler) { This. DataHandler =Ahandler; } @Override Public voidrun () {//TODO auto-generated Method Stub         for(inti = 0; I <5;i++) {Datastring[i]= i+ ""; } datahandler.sendemptymessage (1); //Listener.datacallback (datastring);    }     Public Interfacedatacallbacklisener{ Public voiddatacallback (string[] str); }}

2 of the Code implementation:

 Packagecom.example.testtesttest;ImportOrg.json.JSONArray;ImportCom.example.testtesttest.DataRunnable.dataCallBackLisener;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;Importandroid.app.Activity;Importandroid.app.FragmentTransaction;ImportAndroid.content.DialogInterface;ImportAndroid.content.DialogInterface.OnClickListener;ImportAndroid.support.v4.app.FragmentManager;ImportAndroid.util.Log;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.widget.Button; Public classMainactivityextendsActivityImplementsandroid.view.view.onclicklistener{PrivateButton Button =NULL; PrivateDatacallbacklisener Callbacklistener; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (r.layout.activity_main);/*Jsonarray json = new Jsonarray ();        for (int i =0; i<4; i++) {json.put (i);        } string[] A = {"1", "2", "3"}; LOG.E ("Loooooooooook", a.tostring ());*/Button=(Button) Findviewbyid (R.id.button); Button.setonclicklistener ( This); } @Override Public voidOnClick (View v) {Switch(V.getid ()) { Caser.id.button:datarunnable runnable=NewDatarunnable (NewDatacallbacklisener () {@Override Public voiddatacallback (String str) {//TODO auto-generated Method StubLOG.E ("Hahahaahahahah", str.tostring ()); Button.settext (Str.tostring ()); //Update UI                }            });            Runonuithread (runnable); /*datarunnable runnable = new Datarunnable (handler);            Thread thread = new Thread (runnable); Thread.Start ();*/        /*anotherfragment fragment = new Anotherfragment ();        Android.app.FragmentManager Fragmentmanager = Getfragmentmanager ();        Fragmenttransaction transaction = Fragmentmanager.        BeginTransaction ();        Transaction.replace (r.id.right_layout, fragment); Transaction.commit ();*/                                 Break; default:         Break; }        }                 PublicHandler Handler =NewHandler () { Public voidhandlemessage (android.os.Message msg) {Switch(msg.what) { Case1: Button.settext ("HHH");  Break; default:                     Break;        }            };                }; }
 Packagecom.example.testtesttest;ImportAndroid.os.Handler; Public classDatarunnableImplementsrunnable{PrivateStringBuilder datastring =NewStringBuilder (); PrivateDatacallbacklisener Listener; PrivateHandler DataHandler;  Publicdatarunnable (Datacallbacklisener alistener) { This. Listener =Alistener; }     Publicdatarunnable (Handler ahandler) { This. DataHandler =Ahandler; } @Override Public voidrun () {//TODO auto-generated Method Stub         for(inti = 0; I <5;i++) {datastring.append (i); }        //datahandler.sendemptymessage (1);Listener.datacallback (datastring.tostring ()); }     Public Interfacedatacallbacklisener{ Public voiddatacallback (String str); }}

Note in 2, the thread must be uithread in order to update the control of the main UI

Finally, the understanding of the callback function blog :

http://www.zhihu.com/question/19801131

http://www.jianshu.com/p/cd35ce823602

Http://www.bkjia.com/Androidjc/853632.html

The last article said the noun: interface object??? Do not understand ....

Android Async Thread Update UI

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.