[Official documentation] process and thread, official documentation thread

Source: Internet
Author: User

[Official documentation] process and thread, official documentation thread
Process and thread content in this article

  • Thread
  • Inter-process communication
  • When an application component is started and the application does not run any other components, the Android system uses a single execution thread to start a new Linux Process for the application. By default, all components of the same application run in the same process and thread (called the "Main" Thread. If an application component is started and the application already has a process (because other components of the application exist), the component starts and uses the same execution thread in the process. However, you can schedule other components in the application to run in a separate process and create additional threads for any process.

    This document describes how processes and threads work in Android applications.

    Process

    By default, all components of the same application run in the same process, and most applications do not change this. However, if you find that you need to control the process to which a component belongs, you can perform this operation in the configuration file.

    List file entries for various component elements-<activity>,<service>,<receiver>And<provider>-All supportedandroid:processAttribute, which specifies the process in which the component should run. You can set this attribute so that each component runs in its own process, or make some components share a process, while other components do not. You can also setandroid:processMake the components of different applications run in the same process, provided that these applications share the same Linux User ID and use the same certificate for signing.

    In addition,<application>The element also supportsandroid:processAttribute to set the default values for all components.

    If the memory is insufficient and other processes that provide users with more urgent services require memory, Android may decide to close a process at a certain time. Application components running in the terminated process will also be destroyed. When these components need to run again, the system will restart the process for them.

    When determining which process to terminate, the Android system will weigh their relative importance to users. For example, a process that hosts a visible Activity is more likely to shut down Activity processes that are no longer visible on the hosted screen. Therefore, whether or not to terminate a process depends on the status of the components running in the process. Next, we will introduce the rules used to terminate the process.

    Process Lifecycle

    The Android system will keep the application process as long as possible, but in order to create a process or run a more important process, the old process needs to be cleared to recycle the memory. To determine which processes are retained or terminated, the system puts each process into the importance hierarchy based on the components that are running in the process and the status of these components. If necessary, the system first removes processes with the lowest importance, then processes with less importance, and so on to recycle system resources.

    There are five levels of importance hierarchies. The following list lists various processes based on their importance (the first process is the most important and will be the last terminated process ):

    Based on the importance of the active component in the process, Android evaluates the process as the highest possible level. For example, if a process hosts a service and a visible Activity, the process is evaluated as a visible process rather than a service process.

    In addition, the level of a process may increase because other processes depend on it, that is, the level of the process serving another process will never be lower than the process it serves. For example, if the content provider in process A serves the client in process B, or if the service in process A is bound to the component in process B, process A is always considered at least as important as process B.

    Because the process that runs the service is higher than the process that hosts the background Activity, it is best to start the service for the Activity that starts the long-running operation, rather than simply creating a working thread, this is especially true when an operation may be more persistent than an Activity. For example, if you are uploading an image to a website, you should start the service to upload the image. In this way, you can continue to upload the image in the background even if you exit the Activity. The Service ensures that the operation has at least the "service process" priority no matter what happens to the Activity. Similarly, the broadcast receiver should also use services, rather than simply putting time-consuming and lengthy operations into the thread.

    Thread

    When the application starts, the system creates an execution thread named "main thread" for the application. This thread is very important because it is responsible for assigning events to corresponding user interface gadgets, including drawing events. In addition, it is also an application and Android UI toolkit component (fromandroid.widgetAndandroid.viewSoftware Package components. Therefore, the main thread is also called the UI thread.

    The system will never create a separate thread for each component instance. All components running in the same process are instantiated in the UI thread, and system calls to each component are distributed by this thread. Therefore, the method for responding to the system callback (for example, reporting user operationsonKeyDown()Or the lifecycle callback method) is always running in the UI thread of the process.

    For example, when you touch a button on the screen, the UI thread of the application will assign the touch event to the gadgets, and the gadgets in turn set their press status, and publish invalid requests to the event queue. The UI thread cancels the request from the queue and notifies the gadgets to re-paint themselves.

    When an application executes heavy tasks to respond to user interaction, this single-threaded mode may cause low performance unless the application is correctly implemented. In particular, if the UI thread needs to process all tasks, a long time-consuming operation (for example, network access or database query) will block the entire UI. Once the thread is blocked, no events, including drawing events, will be dispatched. From the user's perspective, the application is displayed as suspended. Even worse, if the UI thread is blocked for more than a few seconds (currently about 5 seconds), the user will see an annoying ANR dialog box. If user dissatisfaction occurs, they may decide to exit and uninstall the application.

    In addition, the Android UI toolkit is not a thread Security Toolkit. Therefore, you must not manipulate the UI through a working thread, but only through the UI thread. Therefore, the single-thread mode of Android must comply with two rules:

    Worker thread

    According to the preceding single-threaded mode, to ensure the application UI response capability, the key is not to block the UI thread. If the executed operations cannot be completed quickly, make sure they are running in a separate thread ("background" or "working" Thread.

    For example, the following code shows a click listener that downloads an image from a separate thread and displays it inImageViewMedium:

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

    At first glance, this code seems to run well because it creates a new thread to process network operations. However, it violates the second rule in single-thread mode: do not access the Android UI toolkit outside the UI thread-this example is modified from the working thread (rather than the UI thread)ImageView. This may lead to unclear and unpredictable behavior, but it is difficult and time-consuming to track this behavior.

    To solve this problem, Android provides several ways to access the UI thread from other threads. The following lists several useful methods:

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

    For example, you can useView.post(Runnable)Method 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();
    }

    Now, the preceding implementation is thread-safe: network operations are completed in a separate thread, while operations are performed in the UI thread.ImageView.

    However, as operations become increasingly complex, such code will become complex and difficult to maintain. To process more complex interactions through a working thread, consider usingHandlerProcess messages from the UI thread. Of course, the best solution may be expansion.AsyncTaskClass, which simplifies the jobs that need to be executed for interaction with the UI.

    Use AsyncTask

    AsyncTaskAllows asynchronous operations on the user interface. It first blocks operations in the working thread and then publishes results in the UI thread, without the need to process the thread and/or the processing program yourself.

    To use it, you must createAsyncTaskSubclass and implementdoInBackground()Callback method, which runs in the background thread pool. To update the UI, you must implementonPostExecute()To passdoInBackground()The returned results are run in the UI thread, so that you can safely update the UI. Later, you can callexecute()To run the task.

    For example, you can useAsyncTaskTo implement the above example:

    public void onClick(View v) {
        new DownloadImageTask().execute("http://example.com/image.png");
    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        /** The system calls this to perform work in a worker thread and
          * delivers it the parameters given to AsyncTask.execute() */
        protected Bitmap doInBackground(String... urls) {
            return loadImageFromNetwork(urls[0]);
        }

        /** The system calls this to perform work in the UI thread and delivers
          * the result from doInBackground() */
        protected void onPostExecute(Bitmap result) {
            mImageView.setImageBitmap(result);
        }
    }

    Now the UI is secure and the code is simplified, because the task is divided into two parts: one part should be completed in the worker thread, and the other part should be completed in the UI thread.

    The following describes how to use AsyncTask.AsyncTaskReference:

    • You can use generics to specify the parameter type, progress value, and task final value.
    • MethoddoInBackground()Will be automatically executed on the worker thread
    • onPreExecute(),onPostExecute()AndonProgressUpdate()All are called in the UI thread
    • doInBackground()The returned value is sentonPostExecute()
    • You candoInBackground()CallingpublishProgress()To be executed in the UI threadonProgressUpdate()
    • You can cancel tasks in any thread at any time

    Note:When working threads are used, another problem may occur, that is, the Activity restarts unexpectedly due to configuration changes during running (for example, the user changes the screen direction), which may destroy the working thread. For more information, see the source code of the example application on the shelf.

    Thread Security Method

    In some cases, the method you implement may be called from multiple threads. Therefore, you must ensure that the method meets the thread security requirements when writing these methods.

    This is mainly applicable to methods that can be called remotely, such as binding methods in services. IfIBinderThe call of the implemented method in comes from the runningIBinderThe same process, the method is executed in the caller's thread. However, if the call is from another process, the method will be executed in a thread selected from the thread pool (rather than in the UI thread of the process). The thread pool isIBinderMaintenance in the same process. For exampleonBind()The method will be called from the service process UI threadonBind()The methods implemented in the returned object (for example, the subclass that implements the RPC method) will still be called from the thread in the thread pool. Since a service can have multiple clients, multiple pool threads may use the sameIBinderMethod. Therefore,IBinderThe method must be implemented as a thread-safe method.

    Similarly, the content provider can receive data requests from other processes. AlthoughContentResolverAndContentProviderClass hides the details of how to manage inter-process communication,ContentProviderMethod (query(),insert(),delete(),update()AndgetType()Method) will be called from the thread pool of the process where the content provider is located, rather than from the UI thread of the process. Since these methods may be called from any number of threads at the same time, they must also be implemented as thread-safe methods.

    Inter-process communication

    Android uses Remote Procedure Call (RPC) to provide an inter-process communication (IPC) mechanism. Through this mechanism, the method called by Activity or other application components will (in other processes) remote execution, and all results will be returned to the caller. This requires that the method call and its data be decomposed to a level that can be identified by the operating system and transmitted from the local process and address space to the remote process and address space, then re-assemble and execute the call in the remote process. Then, the return value is transmitted back in the opposite direction. Android provides all the code required to execute these IPC services, so you only need to focus on defining and implementing the RPC programming interface.

    To execute IPC, you must usebindService()Bind the application to the service. For more information, see the service developer guide.

    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.