Android Development-process and Thread

Source: Internet
Author: User

Directory
  • 1 android in process with thread-Processes and Threads
    • 1.1 Process-Processes
      • Lifetime of the 1.1.1 process
    • 1.2 Threads-Threads
      • 1.2.1 Worker thread-worker threads
      • 1.2.2 Using-asynctask
      • 1.2.3 Thread-Safe methods-Thread-safe methods
    • 1.3 interprocess communication-interprocess communication
Processes and threads in Android-Processes and Threads

When an application starts running its first component, Android launches a Linux process for it and executes a single thread in it. By default, all components of the application run in this thread of the process. However, you can also schedule components to run in other processes, and you can derive other threads from any process.
Here's how to use threads and processes in an Android system.

Process-Processes

By default, all components of the same application run in the same process. However, if you need to control which process a component belongs to, you can do so by modifying the manifest file.
All those items in the manifest file that support the Android:process attribute, such as [activity |],[Service |], and [content provided |] You can specify a process so that the components run in the specified process. You can set this property so that each component runs on its own process or only some of its components share a process. You can also set android:process so that components from different applications can run in the same process-this requires the app to share the same user ID and have the same digital certificate.
Element also supports the Android:process property, which is used to specify a default value for all components.
The Android system may at some point decide to close a process, such as memory is scarce and another process is more pressing to start. When the process is closed, the components are destroyed. If these components are re-required to work, the process is created again.
When deciding which threads to close, the Android system measures how tightly the process is to the user. For example, a process that has no visible activity is more likely to be closed than a process with visual activity. How to determine whether a process is closed depends on the state of the components that are running in the process. The rules for deciding to close a process are discussed below.

Lifetime of the process

The Android system will try to maintain the life of a process until it eventually needs to free up memory for the new, more important process. To determine which process terminates, the system places the process at different levels of importance, depending on the state of the components that are running in-process and the components. When system resources are needed, the lower the importance level is first eliminated.
The level of importance is divided into 5 stalls. Below is a list of the importance levels for different types of processes (the first process type is the most important and the last one will be terminated)
1 Foreground process
The user is currently doing something that requires this process. If the following conditions are met, a process is considered a foreground process:
1) The process has an activity that is interacting with the user (the Onresume () method of the activity is called).
2) This process has a service that is bound to an activity that is interacting with the user.
3) This process has a foreground running Service-service called the Method Startforeground ().
4) This process has a service that is performing any of its life cycle callback methods (OnCreate (), OnStart (), or OnDestroy ()).
5) This process has a broadcastreceiver that is executing its onreceive () method.
Typically, at any point in time, only a few foreground processes exist. They are terminated only when they reach a contradiction that cannot be adjusted-if the memory is too small to continue running. Usually, at this point, the device reaches a memory paging state, so some foreground processes need to be terminated to ensure the user interface response.
2 Visible Processes
A process does not have components running in the foreground, but it can still affect what the user sees. The process is visible when the following conditions are true:
1) This process has an activity that is not in the foreground but is still visible (its OnPause () method is called). This is the case, for example, when a foreground activity launches a dialog box.
2) This process has a service bound to the foreground (or visible) activity. A visible process is extremely important and will not normally be terminated unless memory is insufficient to free up memory for the foreground process to run.
3 Service Process
A process is not within either of these two, but it runs a service that is started by StartService ().
Although a service process does not directly affect what the user sees, they usually do things that the user cares about (such as playing music or downloading data), so a service process is terminated unless the system does not have enough space to run the foreground and visible processes.
4 Background Process
A process has an activity that is currently not visible (the OnStop () method of the activity is called).
Such processes do not directly affect the user experience, so the system can kill them at any time to provide storage space for the foreground, visible, and service processes. There are usually a lot of background processes running. They are stored in an LRU (least recently used) list to ensure that the process that owns the activity that was recently seen is finally killed. If an activity correctly implements its life cycle method and saves its current state, the process that kills it will not affect the user's visual experience. Because when the user returns to the activity, the activity restores all of its visible state.
5 Empty Processes
A process that does not have any active components.
The only reason to keep this type of process is the cache, which can increase the speed at which the next component will run. The system often terminates them in order to balance the overall system resources between the process cache and the underlying kernel cache.

Based on the importance of the components currently active in the process, Android will rank the process at its highest possible level. For example, if a process has a service and a visible activity, the process is determined to be a visible process, not a service process.
In addition, the level of a process may be improved if it is dependent on other processes-a process that serves other processes that cannot be at a lower level than the service process. Because a process with a service is higher than a process level with a background activitie, it is better to start a service rather than simply create a worker thread when an activity initiates an operation that takes a long time to execute. This is especially true when the operation may be longer than the life of the activity. For example, an activity that uploads a picture to a Web site should start a service so that the upload can continue to execute in the background when the user leaves the activity. Using a service ensures that the operation is at least at the "service process" level, without having to worry about whether the activity has been unfortunate. This is also the reason that the broadcast receiver should use the service instead of simply using a thread.

Thread-Threads

When an application is started, the system creates an execution thread called "main". This thread is important because it is responsible for distributing events to user interface controls. Contains drawing events. It's also where your app interacts with the Interface Toolkit (Android.widget and components in the Android.view package). So the main thread is also called the interface thread.
The system does not create threads for each instance of the component individually. All components running in a process are instantiated in the interface thread, and the system's calls to each component are distributed in this thread. Therefore, a method that responds to a system call (such as a onkeydown () or a lifecycle callback method that reports a user's action) is always in process on the interface thread.
For example, when a user touches a button on the screen, your app's interface thread sends the touch event to the control, then the control sets its pressed state and then sends a request to the event queue that its interface becomes invalid, and the interface thread pulls the request out of the queue and notifies the control to redraw itself.
This single-threaded pattern brings low performance when your application performs a large number of operations in response to user interaction, unless you can optimize your program correctly. If everything happens in the interface thread, performing time-consuming operations such as network connections or database requests will prevent the entire interface from responding. When a thread is blocked, it cannot dispatch events, including drawing events. From the user's point of view, the program reacts too slowly. Even worse, if the interface thread is blocked for a few seconds (about 5 seconds), the user complains that the program is unresponsive and the user may exit and delete your app.
In addition, the Andoid interface is not thread-safe. So you can never manipulate your interface in a worker thread-you can only manage your interface in the interface thread. Therefore, there are two simple rules for single-threaded mode:

    1. Do not block interface threads
    2. Do not operate the interface outside the interface thread.
Worker thread-worker threads

Because of the above-mentioned single-threaded mode, it is important not to block your interface threads to keep your application's interface responsive, so if you have tasks that cannot be completed quickly, you should put them in another thread (background thread or worker thread).

For example, the following is the code that responds to the Click event, downloads a picture in another thread, and displays it in a imageview:

public void OnClick (View v) {New Thread (new Runnable () {public void run () {Bitmap b = loadimagefromnetwork ("Http://exam Ple.com/image.png "); Mimageview.setimagebitmap (b); }}). Start ();}


Roughly, this works well because it creates a new thread for network operation. However, it violates the second rule: do not manipulate the interface outside the interface thread. This code modifies the ImageView in the worker thread. This leads to undefined exceptions, and it is difficult to debug the trace.
To correct this problem, Android offers a number of ways to manipulate the interface from other threads. The following are the available methods:

    • Activity.runonuithread (Runnable)
    • View.post (Runnable)
    • View.postdelayed (Runnable,long)

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

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 this implementation is finally thread-safe: The network operation is in another thread and the ImageView changes in the interface thread.
However, as the complexity of operations increases, such code becomes complex and difficult to maintain, and in order to handle more complex interactions, you may need to use the handler object in the thread to handle messages that are passed from the UI threads. But the best solution is to inherit the Asynctask class, which makes it easier to work with threads and UI interactions.

Using-asynctask

Asynctask allows the program to work asynchronously, performing certain operations on a thread, and then returning the results to the UI thread.
When using the Asynctask class, you need to inherit the Asynctask class and implement the Doinbackground () callback method. To update the UI interface, you need to implement OnPostExecute () and get the results from the Doinbackground () method, and finally, you can invoke the Execute () method in the UI thread to perform the operation so that you can safely update the UI interface.
For example, we use Asyntask to implement the above example:

public void OnClick (View v) {new Downloadimagetask (). Execute ("Http://example.com/image.png");} private Class Downloadimagetask extends Asynctaskvoid, bitmap> {protected Bitmap doinbackground (String ... urls) {return LOADIMAGEF Romnetwork (Urls[0]); } protected Voidonpostexecute (Bitmap result) {Mimageview.setimagebitmap (result);}}

Because asynctask divides the work into two parts, both the UI thread and the worker thread do the part of the task that they should do, so we can simply implement a secure UI update task.
For more information on Asynctask please refer to the Asynctask class for a brief description of how it works:

    • Asynctask defines three types of generic type params,progress and result. The params is the input parameter that initiates the task execution, such as the URL of the HTTP request. Progress is the percentage of background task execution. Result is the outcome of the final return of the background execution task, such as String,integer.
    • Doinbackground () is automatically executed in the worker thread.
    • OnPreExecute (), OnPostExecute (), and onprogressupdate () are all three methods that are called in the UI thread.
    • The value returned by the Doinbackground () method is passed to the OnPostExecute () method.
    • You can call the Publishprogress () method at any time in the Doinbackground () method to update the execution progress in the UI thread.
    • You can cancel a task from any thread at any time.

Caution:another problem you might encounter when using a worker thread was unexpected restarts in your activity due to a R Untime configuration change (such as if the user changes the screen orientation), which may destroy your worker thread. Persist your task during one of these restarts and how to properly cancel the task while the activity is Destroyed, see the source code for the shelves sample application.

Thread-Safe Methods-Thread-safe methods

In some cases, the method you implement may be called by multiple threads, so ensure that the method is thread-safe.
Some methods of remote invocation-such as binding services. When we call a method in a running Ibander in the same process, this method runs in the caller's thread. However, when a method in another process is called, the method executes in one of the threads in the thread pool that the system is open for. For example, the binding service is called in the UI thread, and the object returned by Onband () is called in a thread pool. Because a service can have multiple clients, multiple pool threads can make the same IBinder method at the same time. Therefore, the implementation of the IBinder method must be thread-safe.

Similarly, a content provider can receive data requests this originate in other processes. Although the Contentresolver and ContentProvider classes hide the details of how the interprocess communication is managed , ContentProvider methods, respond to those requests-the methods query (), insert (), delete (), update (), and GetType ()- is 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 is implemented to be thre Ad-safe.

interprocess Communication-interprocess communication

Android provides an interprocess communication (IPC) mechanism that uses a remote procedure call (RPC), where one of the methods is called an activity or other application component, but any results returned to the caller are executed in another process. This requires that methods and parameters are called from the address space of the local process and the remote process at the system level, and the return values are passed back in the same way. The Android system perfectly supports interprocess communication (IPC) so you can focus on developing and implementing RPC programming interfaces.
To implement interprocess communication (IPC), an application must be bound to a service that uses Bindservice (). For more information, please refer to the Service Development Guide.

Original address: http://guide.eoeandroid.com/#Processes_and_Threads

Android Development-process and Thread

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.