Today's interview, the interviewer and I talk about synchronous and asynchronous, because talking about synchronization I just think of thread synchronization, and then share the critical resources AH deadlock ah what, so have been saying this, thread async has never heard. Just looked at the ball think of this matter to check, do not know what he said asynchronous is not expecting me to answer with handler to refresh the main thread, I usually call this asynchronous task-yesterday side, the interviewer asked is how to refresh the UI thread, and then I said with Asynctask. Well, that's the case, because I wanted to rewrite the asynctask that I had written before. It is also to let the anxious waiting time too fast point.
Asynchronous task-related
Android from 2.3 (or 3.0 ...?) is not allowed to perform some time-consuming tasks in the main thread at first, we usually need to use an asynchronous task mechanism to solve the problem of refreshing the UI inside a child thread.
Simply translate some of the important classes on the API: (I should ask the interviewer if there are any relevant classes to remind you of)
Message:
Defines a message object that can carry some field or object data, the official recommended instantiation is: Message.obtain ()
MessageQueue:
Queue that holds messages
Handler:
When you create a new handler, he is bound to the MessageQueue created by the current thread. There are two main functions, one is to queue the message, and the other is to process the message.
Looper:
A class that runs the thread message queue, which is not with the message queue by default, can be prepare()
created by and loop()
. The main thread is the one with the message queue.
The process of stealing a piece:
three ways to implement asynchronous tasks
There are three ways to implement asynchronous tasks as I know it:
- Use
Handler + Message
to implement
- Using
AsyncTask
Classes
- Calling
runOnUiThread()
methods
Here's a code comment to illustrate the use of three methods:
Handler+message
Public class mainactivity extends actionbaractivity { PrivateTextView TextView;//Anonymous inner class instantiates a handler object PrivateHandler Handler =NewHandler () {//Override handlemessage method, implement child thread refresh UI through asynchronous message mechanism Public void Handlemessage(Message msg) {Textview.settext ("You Got"+ Msg.what +"through handler"); } };@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); TextView = (TextView) Findviewbyid (R.id.textview);NewTestthread (). Start (); }Private class testthread extends Thread { Private inti =1; Public void Run() { while(true) {/ * Note here that we can get the message object with the message message = Message.obtain () and then call the SendMessage () method with Handler, more detailed methods can refer to api*/ Handler.sendemptymessage (i++);if(I > -) Break;Try{Sleep ( +); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } } } }}
Asynctask
The code for the previous article is posted here directly, because the article should be deleted later.
Public class mainactivity extends actionbaractivity {Private TextView TextView; Private button button; Private Myasynctask Asynctask;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); TextView = (TextView) Findviewbyid (R.id.textview); Button = (button) Findviewbyid (R.id.button); Asynctask =NewMyasynctask ();//Click button to perform an asynchronous taskButton.setonclicklistener (NewOnclicklistener () {@Override Public void OnClick(View arg0) {//TODO auto-generated method stubAsynctask.execute ("Leelit");//This parameter is passed in parameter, commonly used in URL network download, can be empty. } }); }/* Generic class Asynctask has three parameters: Params, incoming parameters, Progress, progress, result, return results. You can also use void to indicate that the parameter is empty. */ Private class myasynctask extends asynctask<String, Void, String> { @Override protectedStringDoinbackground(String ... string) {//TODO auto-generated method stubString conutstring = string[0];//String variable parameter intz =0;//Perform 500 million calculations to simulate a time-consuming task for(inti =0; I <1000000; i++) { for(intj =0; J < -; J + +) {z++; }} conutstring + ="has executed + + computation for"+ z +"Times"; LOG.E ("ProcessInfo","The task is done");returnconutstring;//Returns the result of the calculation to OnPostExecute ()}@Override protected void OnPostExecute(String result) {//TODO auto-generated method stub Super. OnPostExecute (Result); Textview.settext (result);//Refresh UI} } }
If you need to show the progress of a task, you can override another method:
// 可变参数的类型就是泛型的第二个参数,因为我这里不需要所以就是Void@OverrideprotectedvoidonProgressUpdate(Void... values) { // TODO Auto-generated method stub super.onProgressUpdate(values);}
And in the doInBackground()
method call publishProgress()
Runonuithread ()
Call this method directly inside the child thread can realize the operation of the main thread, is the simplest operation
Public class mainactivity extends actionbaractivity { PrivateTextView TextView;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); TextView = (TextView) Findviewbyid (R.id.textview);NewThread (NewRunnable () {@Override Public void Run() {//TODO auto-generated method stub Try{Thread.Sleep ( -); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); }FinalString result ="After a long-time execution";//Can be called directly on a child threadRunonuithread (NewRunnable () { Public void Run() {Textview.settext (result); } }); }}). Start (); }}
Take a look at the source code of this simple method
publicfinalvoidrunOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); else { action.run(); } }
Yes, it can be seen by encapsulating handler to achieve, in fact, Asynctask is the same, but the asynctask mechanism is a bit more complicated.
Summary: Asynchronous tasks can be implemented with handler and their encapsulated classes or methods
Android: Asynchronous Task Basics