Process and thread in Android)

Source: Internet
Author: User

I. Process)

1. by default, each application runs in an independent process, and all components run in the main thread of the process (the main thread is also called the UI thread because it mainly processes the UI)
2. You can use the Android: process attribute of component in the manifest file to specify the running process for the current component. Even components in different applications can run in the same process,
But most applications should not be configured like this unless you really want some of your components to be managed in a separate process.
3. The Android system will kill some processes that he thinks can be killed in the case of insufficient resources to provide resources for the actions being executed by the user,
Generally, process has five importance levels. Low-level processes are killed first.
4. Five importance levels of Process
1) Foreground process: a process with the following features is considered as a foreground process)
① A maximum of one activity in the onresume () Status
② Services bound to activity that interacts with users
③ The highest front-end service is running (the running service that calls startforeground)
④ Services with the highest life cycle method being executed: for example, oncreate (), onstart (), ondestroy ()
⑤ The broadcastreceiver that has the maximum onreceive () method being executed
2) visible process: visible process
① The highest activity is in the onpause () state.
② A front-end service or a service bound to activity
3) service process:
① The highest number of running services is available. These services are started through startservice ().
4) background process:
① Activity with the highest visibility (in onstop () State)
5) Empty Process:
① Only processes with no component are available. These processes are generally used as temporary caches.

Ii. Thread)

1. When an application is started, it runs in the main thread of an independent process. The main thread is a very important thread, which manages the generation, distribution, and processing of events,
The interaction with the application is processed in this thread, so this thread is also called the UI thread)
2. By default, all components in an application are running in the UI thread, and the system calls different components are forwarded through the UI thread. Therefore,
The methods called by the system, such as onclick () and onkeydown (), are all executed in the UI thread.
3. If your application needs to handle long-event operations, the single-threaded mode will reduce your application user experience, especially for network operations and database operations.
They generally take a long time and are easy to block when running in the UI thread. If the UI thread is blocked for more than five seconds in the Android system, the system will throw the notorious application not responding exception.

★★★★★Ui thread purpose:
1. Do not block the UI thread: database operations and network operations should be completed by another thread.
2. do not access the UI Toolkit (ui toolkit is the component in Android. widget and Android. View packages) in other threads except the UI thread)
 

3. worker threads)
1. as mentioned above, do not block the UI thread, so as long as your work is not completed instantaneously, you should set up another thread to implement it: create a new working thread in the event processing function as follows:
Public void onclick (view v ){
New thread (New runnable (){
Public void run (){
Bitmap B = loadimagefromnetwork ("http://example.com/image.png ");
Mimageview. setimagebitmap (B); // The second rule of the UI thread is violated.
}
}). Start ();
}
2. because it cannot be in a thread other than the UI thread, although the above example code opens up a new thread and does not block the UI thread, it operates the component in the UI toolkit in the working thread,
Therefore, the second rule is violated. Android provides a variety of solutions:
1) solution 1: By calling different methods in different locations of the Code, it is a bit of structured programming. A large amount of similar processing will reduce the readability and maintainability of the Code.
① Activity. runonuithread (runnable)
② View. Post (runnable)
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 ();
}

③ View. postdelayed (runnable, long)
 
2) solution 2: Use handler to uniformly process messages for thread scheduling, but it is not the best method.
④ Handler processes the message
 
3) solution 3: asynchronous job asynctask, which may be the best solution
Create a class inherited from asynctask and implement the two methods to process the tasks processed by the worker thread and the tasks processed by the UI thread respectively.
It also avoids the trouble of operating the thread and/or handler by yourself.
Public void onclick (view v ){
New downloadimagetask(cmd.exe cute ("http://example.com/image.png ");
}

Private class downloadimagetask extends asynctask <string, void, bitmap> {
/** The system callthis to perform work in a worker thread and
* Delivers it the parameters given to asynctask.exe cute ()*/
Protected bitmap doinbackground (string... URLs ){
Return loadimagefromnetwork (URLs [0]);
}

/** The system callthis to perform work in the UI thread and delivers
* The result from doinbackground ()*/
Protected void onpostexecute (Bitmap result ){
Mimageview. setimagebitmap (result );
}
}

The following is a quick start for asynctask.
(1). You can specify the type of the parameters, the Progress values, and the final value of the task, Using Generics
(2). The method doinbackground () executes automatically on a worker thread
(3). onpreexecute (), onpostexecute (), and onprogressupdate () are all invoked on the UI thread
(4). the value returned by doinbackground () is sent to onpostexecute ()
(5). You can call publishprogress () at anytime in doinbackground () to execute onprogressupdate () on the UI thread
(6). You can cancel the task at any time, from any thread
★★★★★
Many operations may cause unexpected restart of the Work thread, such as runtime configuration change (for example, if the user changes the screen direction, destroy your work thread and restart it)
In this case, for details about how to correctly persist your tasks and how to correctly cancle tasks, refer to the source code example: shelves
API: http://code.google.com/p/shelves/
Source code can be downloaded from git.

Iv. asynctask: asynchronous task. Android uses it to implement independent processing of UI thread and work thread. recommended method
1) asynctask enables proper and easy use of the UI thread.
This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
 
2) An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.

An asynchronous task is defined by 3 generic types, called Params, progress and result,

And 4 steps, called onpreexecute, doinbackground, onprogressupdate and onpostexecute.

3) asynctask must be subclassed to be used. The subclass will override at least one method (doinbackground (Params ...)),
And most often will override a second one (onpostexecute (result ).)
 
4) Example:
(1) define asynctask
Private class downloadfilestask extends asynctask <URL, integer, long> {
Protected long doinbackground (URL... URLs ){
Int COUNT = URLs. length;
Long totalsize = 0;
For (INT I = 0; I <count; I ++ ){
Totalsize + = Downloader. downloadfile (URLs [I]);
Publishprogress (INT) (I/(float) count) * 100 ));
}
Return totalsize;
}

Protected void onprogressupdate (integer... progress ){
Setprogresspercent (Progress [0]);
}

Protected void onpostexecute (long result ){
Showdialog ("downloaded" + Result + "bytes ");
}
}
(2) Execution
New downloadfilestask(cmd.exe cute (url1, url2, url3 );

5) asynctask's generic types: Significance of generic parameters
The three types used by an asynchronous task are the following:

1. Params, the type of the parameters sent to the task upon execution.
2. Progress, the type of the Progress units published during the background computation.
3. result, the type of the result of the background computation.
 
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type void:
Private class mytask extends asynctask <void, void, void> {...}
 
6) Step 4 of asynctask execution: The 4 steps
When an asynchronous task is executed, the task goes through 4 steps:
1. onpreexecute ()
Invoked on the UI thread immediately after the task is executed.
This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
2. doinbackground (Params ...)
Invoked on the background thread immediately after onpreexecute () finishes executing.

This step is used to perform background computation that can take a long time.

The parameters of the asynchronous task are passed to this step.
The result of the computation must be returned by this step and will be passed back to the last step.
This step can also use publishprogress (Progress...) to publish one or more units of progress.

These values are published on the UI thread, In the onprogressupdate (Progress...) step.
3. onprogressupdate (Progress ...)
Invoked on the UI thread after a call to publishprogress (Progress...). The timing of the execution is undefined.

This method is used to display any form of progress in the user interface while the background computation is still executing.
For instance, it can be used to animate a progress bar or show logs in a text field.
4. onpostexecute (result)
Invoked on the UI thread after the background computation finishes.
The result of the background computation is passed to this step as a parameter.

7) cancelling a task: cancels the execution of the task.
A task can be canceled at any time by invoking cancel (Boolean ).
Invoking this method will cause subsequent callto iscancelled () to return true.
After invoking this method, oncancelled (object ),
Instead of onpostexecute (object) will be invoked after doinbackground (object []) returns.

To ensure that a task is canceled as quickly as possible,
You shoshould always check the return value of iscancelled () periodically from doinbackground (object []),

If possible (inside a loop for instance .)

8) threading rules: a prerequisite for normal asynchronous tasks
There are a few threading rules that must be followed for this class to work properly:
(1). The task instance must be created on the UI thread.
(22.16.exe cute (Params...) must be invoked on the UI thread.
(3). Do not call onpreexecute (), onpostexecute (result), doinbackground (Params...), onprogressupdate (Progress...) manually.
(4). the task can be executed only once (an exception will be thrown if a second execution is attempted .)


9) memory observability: Resources synchronized by threads
Asynctask guarantees that all callback callare synchronized in such a way that the following operations are safe without explicit synchronizations.
(1). Set member fields in the constructor or onpreexecute (), and refer to them in doinbackground (Params ...).

(2). Set member fields in doinbackground (Params...), and refer to them in onprogressupdate (Progress...) and onpostexecute (result ).

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.