Android Doc translation-processes and threads

Source: Internet
Author: User
Tags hosting

Processes and threads

When an application component starts and the application does not have any other components running, the android system starts a new Linux Process for the application with a single thread of execution.
By default, all components of the same application run in the same process and thread (called the "Main" Thread ). if an application component starts and there already exists a process for that application (because another component from the application exists ),
Then the component is started within that process and uses the same thread of execution. however, you can arrange for different components in your application to run in separate processes, and you can create additional threads for any process.

 

When the component of an app is started and no component of the app is running in the system, Android will start a new Linux thread for the app for calculation. By default, all components run in the same thread (called the main thread ). If the app component starts or has started a process, the component will be executed in this thread. However, you can schedule different components in the app to run in scattered threads, and create multiple threads in a process.

 

Processes

By default, all components of the same application run in the same process and most applications shocould not change this. However, if you find that you need to control which process a certain component
Belongs to, you can do so in the manifest file.

 

By default, all components of an app must run in the same process, and most programs cannot change this situation. However, if you find that you need to control some parts of a process, you can modify the manifest file.

 

The manifest entry for each type of component element-<activity>,
<service>,<receiver>, And<provider>-Supports
android:processAttribute that can specify a process in which that component shoshould run. you can set this attribute so that each component runs in its own process or so that some components share a process while others do not. you can also setandroid:process
So that components of different applications run in the same process-provided that the applications share the same Linux User ID and are signed with the same certificates.

 

Each component in manifest,<activity>,
<service>,<receiver>, And<provider>Each hasandroid:processTo specify the process in which the component can run. You can also set this parameter to "each component runs in its own thread" or "when others do not share it, share some processes with others "or" Let components of different programs run in the same process "-this requires the application to provide the same Linux
User ID and the same certificate is indicated.

 

The<application>Element also supports
android:processAttribute, to set a default value that applies to all components.

 

    <application>This element also providesandroid:processThis attribute goes to the default value for all components.

 

Android might decide to shut down a process at some point, when memory is low and required by other processes that are more immediately serving the user. application components running in the process
That's killed are consequently destroyed. A process is started again for those components when there's again work for them to do.

Android will kill some processes when the memory is low, or when the processes that serve users more directly (which are considered as higher-priority processes) require memory. Components running in the process are also killed. A process can start to work only when the component is started again.

 

When deciding which processes to kill, the android system weighs their relative importance to the user. For example, it more readily shuts down a process hosting activities that are no longer visible
On screen, compared to a process hosting visible activities. the demo-whether to terminate a process, therefore, depends on the state of the components running in that process. the rules used to decide which processes to terminate is discussed below.

 

When a process is killed, Android will weigh which processes are important to the system. For example, compared with visible threads, the system is easier to delete processes that save the activity and are no longer displayed on the screen. Therefore, dependent on the components status in these processes. These rules will determine who will be terminated.

Process Lifecycle

The Android system tries to maintain an application process for as long as possible, but eventually needs to remove old processes to reclaim memory for new or more important processes. To determine
Which processes to keep and which to kill, the system places each process into an "importance hierarchy" based on the components running in the process and the state of those components. processes with the lowest importance are eliminated first, then those
With the next lowest importance, and so on, as necessary to recover system resources.

 

The Android system tries its best to maintain an application, but in the end, when the old process needs to be removed to recycle memory for a new and more important process, the process should be killed, the state of these components is very heavy. The lowest priority will be eliminated first, and then the lower priority will be... And so on.

 

There are five levels in the importance hierarchy. The following list presents the different types of processes in order of importance (the first process is
Most importantAnd isKilled last):

There are five important levels below,

1. Foreground process (foreground process ):
The user's current work needs. A process is considered as a foreground process if it meets any of the following conditions: it is running an activity that is interacting with the user (the onresume () method of the activity object has been called ).
A hosted service is bound to an activity that interacts with users.
A service object executes its lifecycle callback (oncreate (), onstart (), and ondestroy ()).
There is a broadcastreceiver object that executes its onreceive () method.
Only a few front-end processes exist within a given period of time. They are killed only as the final measure-if the memory is too low, they cannot continue running.
 

2. Visible process ):
There are no front-end components, but they still affect the user's display on the screen. A process that meets any of the following conditions is considered visible: it hosts a non-foreground activity, but it is still visible to the user (its onpause () method has been called ). For example, this may happen if a foreground activity is still visible after a dialog box (other processes) is run, such as when the input method is popped up.
A service is hosted and bound to a visual activity.
A visible process is considered important and will not be killed, unless to keep the foreground process running.
 

3. Service Process ):

Is a service that runs the startservice () method and does not fall into the above two categories. Although service processes are not directly visible to any users, they usually do things that users care about (such as playing MP3 in the background or downloading data from the Network), so the system keeps them running, unless there is not enough memory to ensure that all foreground and visual processes are running.
 

 

4. background process ):

Is an activity that keeps invisible to users (the onstop () method of the activity object has been called) (if there are other threads running besides the UI thread, it will not be affected ). These processes do not directly affect user experience, and can be killed at any time to reclaim the memory for a foreground, visualized, and service process. Generally, many background processes run, so they are kept in the same LRU (least recently used, that is, the least recently used. If you have learned the operating system, you will feel familiar with it, same as the Memory Page Replacement Algorithm LRU .) List to ensure that the most recently used active process is finally killed.

5. Empty Process ):

Is a process that does not maintain active application components. The only reason to keep this process available is to use it as a cache to speed up the next Startup of components. System Processes kill these processes to balance the system resources between the process cache and the potential kernel cache.

The ranking of a process increases because other processes depend on it. A process serves other processes, and its ranking is never lower than that of the processes it serves. For example, if a customer in process B is a content provider in process A, or a service in process a is bound to a component in process B, process a is always considered to be more important than process B.
Because a service process ranks higher than a background activity process, an activity starts a service to initialize a long running operation, instead of simply deriving a thread-especially if the operation is likely to drag down the activity (for example, ANR appears ). This example is to play music in the background and upload pictures taken by the camera to a website. Use the Service to ensure that the operation has at least the priority of the "service process", no matter what happens to the activity.

Threads

When an application is launched, the system creates a thread of execution for the application, called "main." This thread is very important because it is in charge of dispatching events to the appropriate
User Interface widgets, including drawing events. It is also the thread in which your application interacts with components from the android UI Toolkit (components from
android.widgetAndandroid.viewPackages). As such, the main thread is also sometimes called the UI thread.

When an app is started, the system creates a thread for execution. It is called "main thread ". This thread is very important because it is responsible for event processing and UI interaction. This thread is also used for Android UI toolkit interaction. Therefore, the main thread is also called the UI thread.

 

When the thread is blocked, ANR will appear, so for the android single-thread model.

1. Do not block the UI thread,

2. Do not call the UI control outside the UI thread.

 

Worker threads

 

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();}

 

Aysnctask

 

AsyncTaskAllows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker
Thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

To use it, you must subclass
AsyncTaskAnd implementdoInBackground()Callback method, which runs in a pool of background threads. to update your UI, you should implement
onPostExecute(), Which delivers the result fromdoInBackground()And runs in the UI thread, so you can safely update your UI. You can then run the task by calling
execute()From the UI thread.

To use asynctask, you must inherit asynctask and implementdoInBackground(), Through implementationOnpostexecute () to update the UI, you can callexecute()This method is used to execute the task.

 

 

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);    }}

 

Thread-Safe Methods

In some situations, the methods you implement might be called from more than one thread, and therefore must be written to be thread-safe.

In some cases, the method we implement will be called in multiple threads. Therefore, we need to consider thread security.

 

(The rest will be translated later ...)

This is primarily true for methods that can be called remotely-such as methods in
Bound Service. When a call on a method implemented in
IBinderOriginates in the same process in whichIBinderIs running, the method is executed in the caller's thread.
However, when the call originates in another process, the method is executed in a thread chosen from a pool of threads that the system maintains in the same process as
IBinder(It's not executed in the UI thread of the process). For example, whereas a service'sonBind()
Method wocould be called from the UI thread of the Service's process, methods implemented in the object that
onBind()Returns (for example, a subclass that implements RPC methods) wocould be called from threads in the pool. Because a service can have more than one client,
More than one pool thread can engage the sameIBinderMethod at the same time.
IBinderMethods must, therefore, be implemented to be thread-safe.

 

Similarly, a content provider can receive data requests that originate in other processes. Although
ContentResolverAnd
ContentProviderClasses hide the details of how the interprocess communication is managed,
ContentProviderMethods that respond to those requests-the methods
query(),
insert(),
delete(),
update(), And
getType()-Are called from a pool of threads in the content provider's process, not the UI thread for the process. Because these methods might be called
From any number of threads at the same time, they too must be implemented to be thread-safe.

 

 

 

 

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.