Hello EveryBody, it's time for us to get together again. Now we can't wait to summarize what we want to summarize today, because if we can't use it in practical applications, we can no longer listen to songs and send messages at the same time. In fact, we should all know that today's main character is process and multithreading. Well, if you don't talk about anything else, go to the topic.
I. Classification of Android processes:
1) Foreground process: the Activity or Service used by the Activity to interact with the user. If the system memory is insufficient, the foreground process is killed;
2) visible process: it can be an onPause Activity in the paused state or a Service bound to it, which is visible to the user, but cannot interact with the user because of the loss of focus;
3) Service process: a Service started using the startService method is running. Although it is not visible to users, it is user-related, for example, a user is listening to music on a non-music interface or a file downloaded on a non-download page. The system will terminate the process before the system uses space to run the two processes;
4) background process: the program that stops running the onStop method is not the user's current concern, such as QQ hanging in the background, such a process system is first killed if there is no memory;
5) blank process: a process that does not contain any program component of an application. Such a process system generally does not let it exist;
2. In-depth process and Multithreading
1. ANR errors caused by a single thread:
ANR error Application Not Responding) indicates an error that occurs when the main UI process is blocked for more than five seconds. It will terminate the normal operation of the program, the cause of ANR error is: single thread.
Example:
package com.example.l0902_anr;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {private Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn=(Button) findViewById(R.id.btn); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int count=0; while(count<1000){ count++; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); }}
The running effect is as follows:
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/0621503H9-0.jpg "title =" Capture. JPG "/>
OK. The reason for the above program's problem is a single thread. We can create another thread to handle time-consuming operations, which will not hinder the operations on the main UI:
Modify the above program as follows:
Package com. example. l0902_anr; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; public class MainActivity extends Activity {private Button btn, btn_stop; private Thread thread; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); btn = (Button) findViewById (R. id. btn); btn_stop = (Button) findViewById (R. id. button1); btn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {thread = new Thread (new Runnable () {@ Override public void run () {int count = 0; while (count <1000) {count ++; try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (count) ;}}); thread. start (); // start thread}); btn_stop.setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {thread. stop (); // stop the thread }});}}
The running effect is as follows:
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/0621501125-1.jpg "title =" Capture. JPG "/>
The code is written here, And the ANR error is solved, but there is another new problem. If I want to update the main UI thread using the new thread, can I, let's use the above program to try and add a TextView to receive the auto-increment data in the new thread to see if it can be implemented:
The program is modified as follows:
Package com. example. l0902_anr; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. textView; public class MainActivity extends Activity {private Button btn; private TextView TV; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); btn = (Button) findViewById (R. id. btn); TV = (TextView) findViewById (R. id. TV); btn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {new Thread (new Runnable () {@ Override public void run () {int count = 0; while (count <1000) {count ++; TV. setText (count + ""); // try to update the main UI Thread try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();}}}}). start (); // start thread }});}}
The running effect is as follows:
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/06215060U-2.jpg "title =" Capture. JPG "/>
We can see that the program is accidentally terminated, so other threads cannot change the data of the main UI, unless we look down...
2. Communication between Android threads -- Handler
In fact, communication between Android threads is not just Handler, but also the use of Message, MessageQueue, and logoff. The Android thread communication model is as follows:
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/062150B37-3.png "title =" 2011050608413182.16.png"/>
1) Message: the Message to be transmitted;
2) MessageQueue: the queue that stores messages;
3) Logoff: used to create MessageQueue and use the Message in the loop;
4) Handler: used for message transmission;
Let's look at the example below:
Package com. example. l0902_handler; import android. annotation. suppressLint; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. textView; public class MainActivity extends Activity {private Button btn_start, btn_stop; private TextView TV; private int I = 0; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); btn_start = (Button) findViewById (R. id. button1); btn_stop = (Button) findViewById (R. id. button2); TV = (TextView) findViewById (R. id. textView1); btn_start.setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// start sending the message handler. post (runnabl) ;}}); btn_stop.setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// stop sending a message handler. removeCallbacks (runnabl) ;}}) ;}// create a new thread private Runnable runnabl = new Runnable () {@ Override public void run () {I ++; // use Message to encapsulate messages of non-UI threads. Message m = new Message (); // use the arg1 attribute of Message or arg2 attribute to transmit messages of int type with high efficiency. arg1 = I; // use Handler to send the message handler. sendMessage (m) ;};@ SuppressLint ("HandlerLeak") private Handler handler = new Handler () {public void handleMessage (Message m) {System. out. println (m. arg1); String str = m. arg1 + ""; // Note: Make sure that TextView is of the String type. setText (str); handler. post (runnabl );}};}
The running result is as follows:
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/0621503U8-4.jpg "style =" float: none; "title =" Capture. JPG "/>
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/06215029D-5.jpg "style =" float: none; "title =" Capture 1.JPG"/>
As you can see, is the data on the main UI updated? It's amazing. This is the communication between threads.
Next we will continue to talk about a thread communication mechanism...
3. Simplified multi-thread communication development-AsyncTask
Let's use an example to illustrate how to use AsyncTask:
1) Let's also write an example of a card screen similar to the above ANR error:
Package com. example. l0902_myasynctask; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; public class MainActivity extends Activity {private Button btn1, btn2; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); btn1 = (Button) findViewById (R. id. button1); btn2 = (Button) findViewById (R. id. button2); btn1.setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {try {// more than 5 seconds, in fact, it is the same as the ANR error in the previous example) thread. sleep (7000);} catch (InterruptedException e) {e. printStackTrace () ;}}); btn2.setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {System. out. println ("Hello To EveryOne ");}});}}
The running effect is as follows:
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/0621501117-6.jpg "title =" Capture. JPG "/>
If you change the wait time to less than 5, it is an example of a typical card screen:
Initial interface:
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/0621504E4-7.jpg "title =" Capture. JPG "/>
Click the following button:
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/0621501O2-8.jpg "style =" float: none; "title =" Capture. JPG "/>
Click the button above: it gets stuck, and the screen cannot do anything.
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/0621504102-9.jpg "style =" float: none; "title =" Capture 1.JPG"/>
How many buttons are clicked below the screen, which will be displayed in 5 seconds:
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/062150CN-10.jpg "style =" float: none; "title =" Capture 2.JPG"/>
The above is an example of a classic card screen. How can this problem be solved? Of course: AsyncTask
2) use AsyncTask to create background processes to solve the card screen problem:
The Code is as follows:
MainActivity. java
Package com. example. l0902_myasynctask; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; public class MainActivity extends Activity {private Button btn1, btn2; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); btn1 = (Button) findViewById (R. id. button1); btn2 = (Button) findViewById (R. id. button2); btn1.setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// create AsyncTask and execute new myasynctask(cmd.exe cute ();}}); btn2.setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {System. out. println ("Hello To EveryOne ");}});}}
MyAsyncTask. java:
Package com. example. l0902_myasynctask; import android. OS. asyncTask;/*** create a thread in the background and no screen jamming * @ author asus */public class MyAsyncTask extends AsyncTask <Void, Void, String> {// core method, start a thread @ Override protected String doInVoid in the background... params) {try {Thread. sleep (5000);} catch (InterruptedException e) {e. printStackTrace ();} return null ;}}
The running effect is no longer provided. You can simply describe it, that is, whether we press the screen button or not, the execution button can be output normally, this is because AsyncTask creates a background process to process time-consuming functions without affecting the normal processing of the main UI.
3) Finally, we will summarize an example of using AsyncTask-the progress of downloading the scroll bar:
MainActivity. java:
Package com. example. l0902_usinganysc; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. progressBar; import android. widget. textView; public class MainActivity extends Activity {private Button btn; private ProgressBar bar; private TextView TV; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); btn = (Button) findViewById (R. id. button1); bar = (ProgressBar) findViewById (R. id. progressBar1); TV = (TextView) findViewById (R. id. textView1); TV. setText ("START download"); btn. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {MyAsyncTask my = new MyAsyncTask (TV, bar); my.exe cute ("", "I = ", "Open File"); // start method }});}}
MyAsyncTask. java:
Package com. example. l0902_usinganysc; import android. OS. asyncTask; import android. widget. progressBar; import android. widget. textView;/*** Summary: Parameter Related * @ author asus */public class MyAsyncTask extends AsyncTask <String, Integer, String> {private ProgressBar; private TextView TV; // constructor: Initialize ProgressBar and TextView public MyAsyncTask (TextView TV, ProgressBar bar) {this. bar = bar; this. TV = TV;}/** the parameter of this method cannot be changed. The return type is the same as that of the third parameter. The return type is the same as that of the first parameter * (non-Javadoc) * @ see android. OS. asyncTask # doInParams []) */@ Override protected String doInString... params) {// variable parameter String p1 = params [1]; String p2 = params [2]; int I = 1; for (I = 1; I <= 100; I ++) {try {Thread. sleep (100);} catch (InterruptedException e) {e. printStackTrace ();} publishProgress (I);} return p1 + I + p2; // also used as a parameter for the next method}/** trigger this method when the asynchronous end, the parameter type is the same as that of the third parameter * (non-Javadoc) * @ See android. OS. AsyncTask # onPostExecute (java. lang. Object) */@ Override protected void onPostExecute (String result) {if (result! = Null) {TV. setText ("download completed"/* + result */);} super. onPostExecute (result);}/** trigger when asynchronous starts * (non-Javadoc) * @ see android. OS. asyncTask # onPreExecute () */@ Override protected void onPreExecute () {System. out. println ("Asynchronous Start"); TV. setText ("START download"); super. onPreExecute ();}/** triggered when processing and interacted with the main UI thread. The parameter is consistent with the second parameter * (non-Javadoc) * @ see android. OS. asyncTask # onProgressUpdate (Progress []) */@ Override protected void onProgressUpdate (Integer... values) {// the second variable parameter, which is determined by the parameter of the publishProgress method above. setProgress (values [0]); TV. setText (values [0] + "%"); // This applies to variable parameters. values [1] indicates the second parameter super of publishProgress. onProgressUpdate (values );}}
The running effect is as follows:
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/06215025H-11.jpg "style =" float: none; "title =" Capture. JPG "/>
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/062150MD-12.jpg "style =" float: none; "title =" Capture 1.JPG"/>
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/06215060W-13.jpg "style =" float: none; "title =" Capture 2.JPG"/>
Okay. Today's content is here. I hope it can help you. If you need improvement, please give me more comments and suggestions. I am happy to accept O (strong _ strong) O Haha ~
This article is from the MySpace blog, please be sure to keep this source http://wangzhaoli.blog.51cto.com/7607113/1287545