In Android, how do processes communicate with threads ??

Source: Internet
Author: User

Original article address: process and thread in Android Author: Jiang Peng

In Android, how do processes communicate with threads ??
1. When an android program starts running, a process is started separately.
By default, all the activities or services in this program run in this process.
By default, an android program also has only one process, but there are multiple threads in one process.
2. When an android program starts running, a main thread is created.
This thread is mainly responsible for the display, update, and control interaction of the UI interface, so it is also called the UI thread
3. At the beginning of an android program, a process is represented as a single-thread model-mainthread,
All tasks run in one thread. Therefore, the time consumed for every function called by mainthread should be
The shorter the job, the better. for time-consuming jobs, subthreads should be given to avoid blocking the main thread (ui thread,
Cause ANR in the program.
4. Android single-threaded mode: androidui operations are not thread-safe and must be executed in the UI thread,
If the sub-thread is used directly, an exception occurs.

Is an activity running in a thread? Or, if two activities are not explicitly arranged in different threads,
Is it in the same thread? When you jump from activity to another activity, the activity that jumps out is displayed.
Sleep Status?
Each activity has a process attribute that specifies the process of the activity,
It should be from the default attribute process (application specified, if not specified, it should be the default main process ).
Android has the concept of task, while each activity of the same task forms a stack, and only a standing activity has a chance.
Interaction with users.

When the application component runs for the first time, Android starts a Linux Process with only one execution thread. By default, all components of the application run in this process and thread. However, you can schedule components to run in other processes, and you can derive other threads from the process. This article describes the processes and threads of Android from the following points:

1. Process

The process in which the component runs is controlled by the configuration file. The component elements <activity>, <service>, <javaser>, and <provider> all have a process attribute that specifies the process in which the component runs. This attribute can be set for each component to run in its own process, or some components share a process while others do not share. They can also set components for different applications to run in the same process-assuming that these applications share the same Linux User ID and are assigned the same permissions. <Application> the element also has the process attribute, which sets a default value for all components.

All components are instantiated in the main thread of a specific process, and the system call component is dispatched by the main thread. No separate thread will be created for each instance. Therefore, the methods corresponding to these calls-such as view. onkeydown () Reports user behavior and lifecycle notifications, always running in the main thread of the process. This means that no component should be executed for a long time or blocking operation (such as network operations or cyclic computing) When called by the system, because it will block other components in the process. You can derive independent threads for long operations.

Public BooleanOnkeydown(INT keycode, keyevent event): keyevent. Callback. onkeymultiple () is implemented by default. It is executed when keycode_dpad_center or keycode_enter of the view is pressed and then released. If the view is available, click.

Parameters

Keycode-Indicates the key code for the button to be pressed, from keyevent
Event-Keyevent Object Defining button actions

Return Value

If you process an event, true is returned. If you want the next receiver to process the event, false is returned.

When the memory remaining is small and other processes request a large amount of memory and need to be allocated immediately, Android recycles some processes and the application components in the process will be destroyed. When they run again, a new process is started.

When determining which process to terminate, Android will weigh their relative weights for user importance. For example, compared with an active process running on the screen (foreground process), it is easier to close a process, and its activity is invisible on the screen (background process ). Deciding whether to terminate a process depends on the component Status in the process. The component status will be described in the following section --Component lifecycle.

2. threads

Although you may restrict your application to one process, sometimes you need to derive a thread to do some background work. Because the user interface must quickly respond to user operations, the active host thread should not perform some time-consuming operations such as network download. Any operations that cannot be completed in a short time should be allocated to other threads.

A thread is created using a standard Java thread object in the code, android provides some convenient classes to manage threads-Logoff is used to run message loops in the thread, Handler users process messages, and handlerthread users set a message loop thread.

Logoff class

This type of user runs a message loop in the thread. The thread does not have a message loop by default. You can call prepare () in the thread to create a running loop, and call loop () to process the message until the loop ends. Most messages are cyclically interacted through the handler class. The following is a typical example of executing a logoff thread. Prepare () and loop () are used to create an initial handler to interact with the Logoff:

Class looperthread extends thread {
Public handler mhandler;

Public void run (){
Logoff. Prepare ();

Mhandler = new handler (){
Public void handlemessage (Message MSG ){
// Process incoming messages here
}
};

Logoff. Loop ();
}
}

For more information about logoff and handler and handlerthread, see related materials.

2.1 Remote Procedure Call (rpcs)

Android has a lightweight Remote Process calling mechanism-the method is called locally but executed remotely (in another process), and the result is returned to the caller. This requires that the method call and its accompanying data be broken down into layers that the operating system can understand, transfer from the local process and address space to the remote process and address space, and re-assemble the call. The return value is transmitted in the opposite direction. Android provides all the code to do this, so that we can focus on defining and executing the RPC interface itself.

An RPC interface only contains methods. All methods are executed synchronously (the local method is blocked until the remote method execution is completed), even if no return value is returned. In short, this mechanism works as follows: First, you declare an RPC interface you want to implement with simple IDL (Interface Definition Language. From this declaration, the aidl tool generates a Java Interface Definition and provides it to local and remote processes. It contains two internal classes, as shown in:

Internal classes have all the code required to manage remote process calls using the APIS defined by IDL. Both internal classes implement the ibinder interface. One of them is used locally in the system. You can ignore it when writing code. The other is stub, which is extended from the binder class. In addition to the internal code used to effectively call Interprocess Communication, the internal class also contains the method declaration in the RPC interface declaration. You can define the subclass of stub to implement these methods, as shown in.

In general, a remote process has a service management (because the service can notify the system about the process and other processes connected to it ). It has the interface file generated by the aidl tool and the RPC method implemented by the stub subclass. The service client only has interface files generated by the aidl tool.

The following describes how to establish a connection between a service and its client:

  • The client of the service (on the local end) should implement the onserviceconnected () and onservicedisconnected () methods, so it will be notified when the connection is established successfully and disconnected from the remote service. Then call bindservice () to establish a connection.
  • The onbind () method of the service is implemented to accept or reject connections, depending on the intent it accepts (the intent is sent to binservive ()). If the connection is accepted, it returns an instance of the stub subclass.
  • If the service accepts the connection, Android calls the onserviceconnected () method of the client and passes it an ibinder object, and returns a proxy of the stub subclass managed by the Service. Through proxy, the client can call the remote service.

Here is a simple description, omitting the details of the RPC mechanism. You can refer to the relevant materials or continue to follow the android development journey, which will be provided later.

2.2. Thread Security Method

In some cases, the method you implement may be called by more than one thread, so it must be written as thread-safe. This is correct for Remote Call methods-as discussed in the previous section. When a method implemented in an ibinder object is called from the ibinder process, this method is executed in the caller's thread. However, when called from another process, the method selects an execution in the thread pool of the ibinder process maintained by Android, which is not executed in the main thread of the process. For example, the onbind () method of a service is called in the main thread of the service process, and the method executed in the object returned by onbind () (for example, the stub subclass that implements the RPC method) will be called in the thread pool. Since the service can have more than one client, more than one thread can simultaneously execute the same ibinder method. Therefore, the ibinder method must be thread-safe.

Similarly, a content provider can accept data requests generated by other processes. Although the contentresolver and contentprovider classes hide how processes communicate, the request contentresolver methods include query (), insert (), delete (), update (), GetType (), it is called in the thread pool of the content provider process, rather than in the main thread of the process. Because these methods can be called from any number of threads at the same time, they must also be thread-safe.

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.