Android processes and threads (3) thread security issues

Source: Internet
Author: User

When a program starts, the system creates a thread named main for the program. This thread is important because it is responsible for distributing events to appropriate user components, including plotting events. In addition, this thread is also the thread for your program to interact with components in the Android UI Toolkit (such as components in android. widget and android. view. Because of this, this main thread is also called the UI thread.

The system does not create a separate thread for each instance of the component. All components running in the same process are instantiated in the UI thread, and the system calls these components are distributed by the UI. Therefore, the methods that respond to system Callbacks are all running in the UI thread of the process (for example, the onKeyDown () method used to report user operations or the lifecycle callback method ).

For example, when a user presses a button on the screen, the UI thread of your program will distribute the touch screen event to the button component, and then the component will set its pressing status in sequence, andEvent queueSend an invalid request (post an invalidate request to the event queue ). Then the UI thread pops up the request and notifies the component to re-paint it.

When your program executes operations frequently in response to user events, unless you can implement your program properly, it may bring a poor user experience. In particular, if all the work in the program is completed in the main thread, operations that take a long time like accessing the internet or database will block the entire UI. When the UI thread is blocked, all events cannot be distributed, including drawing events. From the user's point of view, this program is like terminating. Even worse, if the UI thread is blocked for more than five seconds, an "application not responing" (ANR) dialog box will pop up. Then the user may decide to abandon your program or even choose to uninstall it.

In addition, the Android UI toolkit is NOT thread-safe. Therefore, you cannot process the UI in other threads, and all your UI work should be completed in the UI thread. Here, there are two rules for the Android single-thread model:

1. Do not block the UI thread

2. Do not access Android UI toolkit outside the UI thread

Worker thread

It is precisely because of the single-thread model discussed above that you will never block the UI thread for the response speed of the program. If the job you want to do is not completed instantly, you shouldNew thread("Background" or "worker" Thread.

For example, the following is the code about clicking a listener to download an image in a separate thread and displaying the image using ImageView:

public void onClick(View v){new Thread(new Runnable(){Bitma b = loadImageFromNetwork("http://examble.com/image.png");mImageView.setImageBitmap(b);}).start();}

At first glance, this code seems to be okay. It creates a new thread to handle online operations. However, it violates the second rule above: the Android UI tookit cannot be accessed outside the Ui thread, because in this example, the ImageView is modified in the new worker thread, rather than in the UI thread. This will lead to undefined or unexpected behavior, which will be difficult and time-consuming to find this error.

To solve this problem, Android provides the following method to access the UI thread from other threads. The specific method is as follows:

Activity.runOnUiThread(Runnable)View.post(Runnable)View.postDelayed(Runnable, long)

For example, you can use View. post (Runnable) to fix the above Code:

public void onClick(View v){new Thread(new Runnable(){public void run(){final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");mImageView.post(new Runnable(){public void run(){mImageView.setImageBitmap(bitmap);}});}}).start();}

The current implementation method isThread SecurityYes: networking operations are completed in a separate thread, while ImageView processing is completed in the UI thread.

However, as the operation complexity increases, the above Code may become complex and not easy to maintain. To use the worker thread to process more complex operations, you can consider using Handler in your worker thread to process messages distributed from the UI thread. Perhaps the best way is to inheritAsyncTaskThis class simplifies the process in which worker threads need to interact with the UI. The following describes how to use AsyncTask.

AsyncTask allows you to executeAsynchronous. It executes time-consuming operations in the worker thread and updates the results in the UI thread. In this process, you do not need to process the thread or handlers.

To use AsyncTask, you must inherit AsyncTask and implementDoInBackgroundCallback method. These callback methods run in the backend thread pool (run in a pool of background threads ). To update your UI, you should implementOnPostExecute() Method. This method passes the processing result in the doinbackground () method to the UI thread, so that you can safely update your UI. Then you can callExecute() Method to implement this entire process.

For example, you can use asynctask to modify the above Code:

Public void onclick (view v) {New downloadimagetask(cmd.exe cute ("http://example.com/image.png");} private class downloadimagetask extends asynctask <string, void, bitmap> {/** The Sytem callthis to perform work in worker thread and delivers it the parameters given to asynctask.exe cute () */procted bitmap doinbackground (string... URLs) {return loadimagefromnetwork (URLs [0]);}/** the system calls this method to update the UI thread and () */protected void onpostexecute (Bitmap result) {mimageview. setimagebitmap (result );}}

Now the UI is secure and the code is simpler. The following is a brief introduction to asynctask:

-You can useGenericTo specify the parameter type, the Progress value (the progress values) and the final value of the task.

-Method doInBackground () will be automatically executed in the worker thread

-The onPreExecute (), onPostExecute (), and onProgressUpdate () methods are all triggered in the UI thread.

-The results of the doInBackground () method are returned to the onPostExecute () method.

-In the doInbackground () method, you can call publishprogress () at any time to execute onProgressUpdate () in the main thread ()

-You can cancel the current task from any thread.

Note that when the worker thread is used, the worker thread may restart due to a change in the configuration during device running (such as screen flip.


Reference: http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html

Related Article

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.