2.APP Components-processes and Threads

Source: Internet
Author: User

1. Processes and Threads

When a application component starts and the application does not has any other components running, the Android system St Arts A new

Linux process for the application with a single thread of execution. By default, any 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 was started within that process and uses the SA Me thread

of execution. However, you can arrange for different, the your application to run in separate processes, and you can create

Additional threads for any process.

2. Processes

The manifest entry for each type of component element- <activity> , <service> <receiver> ,, and -supports android:process an

attribute that can specify a process in which that component should run.

You can also set android:process So, the different applications run in the same process-provided the app Lications

Share the same Linux user ID and is signed with the same certificates.

2.1 Process Lifecycle

The Android system tries to maintain a application process for as long as possible, but eventually needs to remove old PR Ocesses to

Reclaim memory for new or more important processes.

The following list presents the different types of processes in order of importance (the first process was most Importa NT and is killedlast):

<1> Foreground Process

A process that's required for, the user is currently doing

<2> Visible Process

A process that doesn ' t has any foreground components, but still can affect what the user sees on screen. (OnPause)

<3> Service Process

StartService ()

<4> Background Process

OnStop ()

<5> Empty Process

3. Threads

Threre is simply the rules to Android's single thread model:

<1> do not block the UI thread

<2> don't access the Android UI Toolkit from outside the UI thread

3.1 Worker Threads

For example, below are some code for a click listener that downloads an image from a separate thread and displays it in an ImageView:

 Public void OnClick (View v) {    new Thread (new  Runnable () {        publicvoid  Run () {            = loadimagefromnetwork ("http://example.com/image.png") );            Mimageview.setimagebitmap (b);        }    }). Start ();}

At first, this seems to work fine, because it creates a new thread to handle the network operation. However, it violates the second

Rule of the single-threaded model: Do not access the Android UI Toolkit from outside the UI thread-this sample mo Difies the

      ImageViewFrom the worker thread instead of the UI thread. This can result in undefined and unexpected behavior, which can is

Difficult and time-consuming to track down

To handle more complex interactions with a worker thread, you might consider using a Handler in your worker thread, To process

messages delivered from the UI thread. Perhaps the best solution, though, was to extend the AsyncTask class, which simplifies the

Execution of worker thread tasks this need to interact with the UI.

3.2 Using Asynctask

    AsyncTaskAllows perform asynchronous work on your user interface. It performs the blocking operations in a worker thread

And then publishes the results in the UI thread, without requiring you to handle threads and/or handlers yourself .

To use it, you must subclass AsyncTask and doInBackground() Implement the callback method, which runs in a pool of Background

Threads.

to update your UI, should implement onPostExecute() , which doInBackground() delivers the result from and run s in the UI thread,

So you can safely update your UI. You can then run the task by calling execute() from the UI thread.

For example, you can implement the previous example using this to AsyncTask :

 Public voidOnClick (View v) {NewDownloadimagetask (). Execute ("Http://example.com/image.png");}Private classDownloadimagetask extends Asynctask<string, Void, bitmap> {    /** The system calls the perform work in a worker thread and * delivers it the parameters given to Asynctask.ex Ecute ()*/    protectedBitmap doinbackground (String ... urls) {returnLoadimagefromnetwork (urls[0]); }        /** The system calls the perform work in the UI thread and delivers * The result from Doinbackground ()*/    protected voidOnPostExecute (Bitmap result) {Mimageview.setimagebitmap (result); }}

4. Thread-safe Methods

In some situations, the methods you implement might is called from more than one thread, and therefore must is written to Be

Thread-safe.

This is the primarily true for methods so can be called Remotely-such as methods in a bound service. When a-call on a method implemented

IBinder IBinder in a originates in the same process in which the was running, the method is executed in the caller ' s thread. H Owever,

When the call originates in another process, the method was executed in a thread chosen from a pool of threads that the SYS Tem

Maintains in the same process as the IBinder (it's not executed in the UI thread of the process). For example, whereas a service ' s

    onBind()Method would is 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) would is called from threads in the pool. Because A service can has more

than one client, more than one pool thread can engage the same IBinder method at the same time. Methods IBinder must, therefor E

Be implemented to be thread-safe.

Similarly, a content provider can receive data requests this originate in other processes. Although the and ContentResolver ContentProvider

Classes hide the details of how the interprocess communication are managed, ContentProvider methods 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,

The UI thread for the process. Because These methods might be called from any number of threads at the same time, they too

Must is implemented to be thread-safe.

5. Interprocess communication

Android offers a mechanism for interprocess communication (IPC) using Remote Procedure Calls (RPCs), in Which a method is called

Activity or other application component, but executed remotely (in another process), with any result returned BAC K to the caller. This

Entails decomposing a method call and its data to a level the operating system can understand, transmitting it from the LO Cal Process

and address space to the remote process and address space, then reassembling and reenacting the call there. Return values is then

Transmitted in the opposite direction. Android provides all the code to perform these IPC transactions, so can focus on defining

and implementing the RPC programming interface.

To perform IPC, your application must bind to a service, using bindService() .

    

2.APP Components-processes and Threads

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.