Android thread processing, android thread
I believe everyone has a certain understanding of JAVA threads. In this article, we will discuss thread issues in Android. I will not repeat the differences between threads and processes, if you are interested, you can refer to Baidu for a detailed explanation. I believe you can often hear about threads. Let's take a look at it.
Why do we need to understand the thread mechanism of Android? In order to improve Android security, Google requires Versions later than Android. If you need network access, declare it. We all know that network access is a time-consuming operation, so we need to add network access to the subthread for processing, and then upload the data of the subthread to the main thread for display.
The following is a simple example to illustrate why the subthread cannot update the View:
@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); textview = (TextView) findViewById (R. id. textview);/** the subthread cannot update the view */new Thread (new Runnable () {@ Override public void run () {try {Thread. sleep (1000); // simulate network loading} catch (InterruptedException e) {e. printStackTrace ();} textview. setText ("Update View ");}}). start ();
}
In this way, the system will be forced back:
Locat Error Log:
The cause of this error is that the sub-thread cannot update the UI interface, and the UI interface must be updated in the main thread. So how can this be said to return from the sub-thread to the main thread? The method is actually very simple. Let's take a look at the two methods to complete the above UI updates.
Method 1: Use runOnUiThread (new Runnable () {}); to achieve:
// Method 1 of updating the view: new Thread (new Runnable () {@ Override public void run () {try {Thread. sleep (1000); // simulate network loading} catch (InterruptedException e) {e. printStackTrace ();} // returns the main thread runOnUiThread (new Runnable () {@ Override public void run () {textview. setText ("Update view method 1 ");}});}}). start ();
In this way, the UI is updated.
Method 2: Use the Handler class to implement:
First, we need to create a Handler object to update the UI through this object.
// Create a Handler object
Private Handler handler = new Handler ();
// Method 2: new Thread (new Runnable () {@ Override public void run () {try {Thread. sleep (3000); // simulate network loading} catch (InterruptedException e) {e. printStackTrace ();} handler. post (new Runnable () {@ Override public void run () {textview. setText ("method 2 for updating views ");}});}}). start ();
Both Chinese methods are very powerful. I personally prefer the first method. However, the UI update via Handler is very powerful. In the subsequent summary, I will introduce Handler's method and strength in processing thread problems. If you are interested in this, you can continue to pay attention to updates.