Android tasks, processes, and threads

Source: Internet
Author: User
Tags hosting

tasks, processes, and threads
About the components and applications in Android, previously involved, mostly static concepts. When an application runs, it is inevitable that you will need to be concerned about the concepts of processes and threads. In Android, the dynamic operation of components, there is a most unusual concept, is the task, translated into tasks, should be more logical.
Task intervention, the most important role is the connection between components, from the details of the process concept stripped out, can be configured with a different model of things, in many cases, can simplify the understanding of the upper-level developers, to help people better development and configuration.

Task
In the SDK for Task (Guide/topics/fundamentals.html#acttask), there is a good analogy, that the task is equivalent to the concept of application (application). In the eyes of developers, the development of an Android program is to do a single detached family component, but for the average user, they perceive is only a running overall application, the whole behind, is the task.
Task, simply put, is a collection of activity components that are clustered together in a stack of patterns. They have potential pre-and post-drive associations, the newly added activity component, at the top of the stack, and only activity at the top of the stack, before they have the opportunity to interact with the user. When the activity at the top of the stack completes its mission, the task will pull it out and let the next activity that will run to the top of the stack come to the user, until no more activity,task ends in the stack.

Event Task Stack

Click to open the email application and enter the Inbox (Activity a) a
Select an email, click View Details (Activity B) AB
Click Reply to start writing new mail (Activity C) ABC
Write a few lines of text, click Select Contacts, go to select Contact Interface (Activity D) ABCD
Select a contact, continue to write e-mail ABC
Write good mail, send complete, back to original mail AB
Click Back to return to Inbox A
Exit email program NULL

As shown in the table above, is an instance. The task stack changes from the beginning of the user's entry to the mailbox to the completion of the reply, exiting the application process. This is a standard stack mode, and for most situations, such a task model is enough to cope, but it can be a lot more brutal when it comes to actual performance, overhead, and so on. For example, starting a browser, in Android is a heavy process, it needs to do a lot of initialization work, and there will be no small memory overhead. But at the same time, using the browser to open some content, but also the general application will have a demand. Imagine, if there are 10 running applications (which will correspond to multiple tasks), you need to start the browser, it will be a cruel scene, 10 task stacks are stacked with very similar browser activity, is how gorgeous a kind of waste ah. So you have the idea that browser activity can exist as a single task, regardless of the request from that task, the browser's task will not be merged into the past. In this way, although the browser activity itself needs to maintain more state, but the overall cost will be greatly reduced, this home for everyone's behavior, is still worthy of praise.
So worthy of the praise of the behavior, Android will certainly raise both hands support. In Android, each activity's task mode is available by the activity provider (via config file ...). ) and activity consumer (via flag information in intent ... ) for configuration and selection. Of course, the user's control over the activity is limited to the extent permitted by the provider, the provider expressly prohibits the mode, the user is not able to cross-border use.
In the SDK (Guide/topics/fundamentals.html#acttask), the two implementation of the task mode configuration of the way, write very clear, I would like to choose some to explain (complete configurable items, must look at the SDK, Here are just a few of the common items ... )。 The provider's configuration of the component is done through the configuration file (Manifest) <activity> item, and the caller is chosen by the flag of the intent object. Compared to the standard task stack pattern, the configuration has two main directions: one is to break out rules, or styles for existing stacks, and another is to open up new task stacks to complete tasks that should be done in the same task stack.
For application developers, the Launchmode attribute in,<activity> needs to be dealt with frequently. It has four modes: "Standard", "Singletop", "Singletask", "singleinstance".
Standard mode, which is the default, is the normal task mode, and with no other factors, activity using this mode constructs an instance of activity that is added to the caller's task stack, The standard mode is undoubtedly the most appropriate for an activity that uses a general overhead generally, because it is logically simple and clear, so it is the default choice.
The Singletop model, which is basically consistent with the standard, differs only when the requested activity is at the top of the stack. At this point, the activity configured as Singletop no longer constructs a new instance into the task stack, but instead sends the new intent to the top of the stack activity, The activity at the top of the stack can be overloaded with onnewintent to deal with new intent (or, of course, ignore ...). )。 This mode reduces some of the duplication overhead at the top of the stack, and avoids some bizarre behavior (imagine how the user experience would be if several of the same activities were the same activity at the top of the stack, and then the first level exits) ... ), well suited to some of the list activity shows that will have an update. A living example is that the browser (Browser) bookmarks activity (browserbookmarkpage) is used in the Android default app, Singletop.
Singletop mode, while destroying the logic of the original stack (reusing the top of the stack, without constructing a new element into the stack ...) ), but did not open a dedicated task. and Singletask, and singleinstance, are taken to another task of the trail. The activity marked as Singletask, at most one instance exists, and is located in the task with which it is rooted. All requests for the activity are skipped to the activity's task. Singletask, much like the concept of a single-piece pattern, all modifications are based on an instance, which is often used in activity where the construction cost is large but the switching cost is small. In the Android source application, this mode is widely used, the most typical example, or the browser application of the main activity (named browser ... ), which is the window that displays the current tab content of the current page. Its construction cost is large, but the page switch or is faster, in the Singletask match, or quite in a fit of heaven.
By contrast, SingleInstance appears to be more extreme. Most of the time singleinstance and Singletask are exactly the same, the only difference being that the activity of singleinstance is the only activity in its stack, and if other activity is involved, are transferred to other tasks. This makes SingleInstance's activity, like an island, a complete black box, which does not care about where the request comes from or who is to follow. In the Android default application, very few such activity, in my personal engineering practice, has tried in Youdao Dictionary's fast to take the word activity used, because I think the fast access to the word entry is convenient (from notification), And will be used on all occasions, should be completely independent.
In addition to the Launchmode can be used to provision task,<activity> another property taskaffinity, is also often used. Taskaffinity, a flock of birds, is inclined to throw into the same task the same activity as the Taskaffinity property. However, its binding force is much weaker than that of Launchmode. It only takes effect if the Allowtaskreparen ting in <activity> is set to TRUE or if the caller adds the Flag_activity_new_task attribute to the intent flag. If you have the opportunity to use the Android notification mechanism to know that every ACTIVITY triggered by notification, it must be a flag_activity_new_task intent to invoke. At this point, developers will most likely need to properly configure the Taskaffinity property so that the called activity can find the organization and run in the same taskaffinity task.

process
In the development of most other platforms, each developer has a very clear understanding of the process model that they apply. For example, a console program, you can imagine it starts a process from the main function, to the end of the main function, process execution completion exit; In a UI program, there is often a message loop running, and when the exit message is accepted, the message loop ends the process. In the process of running the program, started what process, and third-party processes to communicate, and so on, each developer is the heart of a mirror of the account is clearly. Process boundaries, where, like the national boundaries, each crossing will leave a deep imprint.
In an Android program, developers can perceive directly, often as tasks. Clarity is the component boundary, and process boundaries become hard to figure out, even with the process of hosting one said. Not only does Android deprive the power of hand-forged memory, but it also does not hesitate to monopolize the process of manual disposal.
Of course, Android hides the details of the process, not deliberately, but naturally. If we refer to traditional applications as process-oriented development, then, in Android, we are doing component-oriented development. From the previous content can be known that the Android components of the jump and communication, are in the premise of third-party intervention, because of this intervention, so that two components are generally not directly connected (service communication, is not required third-party intervention, So Android assumes that it's all a cross-process boundary, unified RPC-based communication, which is also to mask the details of the process ... ), and whether or not it crosses the process boundary becomes unimportant. So, if it's time for developers to focus on the process, it's weird and confusing, and Android has all the processes in place, and the upper layers don't need to know the life and death of the process and the details of the communication.
At the bottom of Android, the process constructs a running pool at the base, not just the individual activity components in the task, but the other three component service, Content Provider, broadcast Receiver, are hosted in one of the underlying processes, to operate. In this case, the process is more like a pool of resources (the concept of the thread pool, the upper layer to use the time to take one out of the good, rather than focus on the specific take which ... ), just to carry the individual components of the run, and the individual components of the direct logical relationship, they do not care. But we can imagine that, in order to ensure integrity, by default, Android will certainly tend to throw the same task, the components of the same application into the same process, but of course, for efficiency reasons, Android is also allowing developers to configure.
In Android, the overall <application> (which will affect each of the components ... ) and the next components can be set <process> properties, the same <process> property components will be thrown into the same process to run. The most common use scenario is to plug the different related applications into a process by configuring <application> 's process properties, so that they can be die. There is a component that will often communicate with a service component into the same process, because with service communication is a dense operation, go to RPC, the overhead is not small, through the configuration, can become a direct reference within the process, consumption is quite small.
In addition to the <process> properties, there are special configuration items for different components, with content provider as an example (configured by <provider>) ... )。 The <provider> item has a Mutiprocess property with a default value of false, which means that content provider only constructs an instance of the process in which the component is provided, and the third party wants to use it to transfer data via RPC. This mode is very useful for applications where the overhead of construction is large and the data transfer overhead is small, and may improve the effect of caching. However, if the data transfer is very large, or if you want to improve the efficiency of the transfer, you need to set mutiprocess to true, so that the Content provider will be in every process to call it to construct an instance, to avoid the overhead of process communication.
Now that the Android system is helping developers to host the process, a whole set of algorithms is needed to implement the recycling logic. The life and death of each process in Android is closely linked to the various components that run in it, and processes are queued to a priority system based on the characteristics of their components, from low-priority to high-priority recycling when they need to be recycled. The Android process is divided into five priority categories: Foreground process, Visible process, Service process, Background process, Empty process. As the name implies, it shows that the more users are connected to the user, the more they interact with the user, the higher the priority, the more difficult it is to be recycled. For specific details, see: Guide/topics/fundamentals.html#proclife.
With priority, a good recycling time is also required. Recovery is too early, the cache hit probability is low may cause the continuous process of destruction of the creation process, the advantages of the pool is gone; the recovery is too late, the overall cost is big, the system operation efficiency is reduced, the good Ferrari may be spoiled as a QQ classic car. Android Process Recycling, the most important thing is to consider memory overhead, as well as other resource conditions such as power, in addition to the number of components per process, the number of processes opened by a single application, and other quantitative indicators, is also an important indicator of measurement. In addition, some runtime time overhead, is also strictly monitored, the slow start process will be forced to kill off. Android will periodically check the above parameters, but also in some very likely to occur at the time of process recovery, such as a component after the completion of the attempt to do recycling.
From the user experience point of view, the Android process mechanism, there will be a very welcome side, some programs start very slow, but in the premise of abundant resources, you repeatedly quit and then use, then start to become extremely fast (the process is not dead, just from backstage to get the front desk), this is the blessing of the process of hosting. Of course, the other side of the welcome is sad, Android's hosting algorithm, but also from time to time to show its naïve side, clearly the user has obviously felt the operating system running speed down, open Task Manager, a ticket application also lively jumping, must manually help them to end life to find the tomb, This makes the task manager basically a prerequisite software for Android.
From a development perspective, the Android process mechanism frees up the developer's hands and feet. Developers do not need to deliberate the construction of a background process secretly silently listen to a time, and try to use a variety of guardian means, the process of forging their own as if the dead bird a FAI general, the process of life and death problems, has been the principle of ordinary developers need to manage the scope. But at the same time, as with the controversy over GC and human memory management, all developers do not believe that algorithms can be more efficient and better than themselves. But I have always believed that the advantages of all efficiency will disappear with the continuous improvement of the algorithm hardware, only the simplicity of the development model will not change with time.

Component Life cycle
Any changes in the architecture will lead to changes in the upper-level development paradigm, and the Android process model, although it eliminates the need for developers to pay close attention to the creation and destruction of processes, still needs to focus on the impact of these point-in-time components. For example, you may need to persist the contents of the memory to the hard disk before the process is destroyed, which requires attention to some of the events that occurred before the process exited.
In Android, you must understand the component lifecycle (components lifecycles) to grasp these points in time. The so-called component of life in the cycle, is the component in front of the background switch, by the user to create the exit, the system is recycled and so on, there will be some events notified to the corresponding component, the developer can selectively handle these events at the corresponding point in time to complete some additional work.
In addition to the content Provider, other components will have the concept of life cycle, all need to follow this model timed fixed-point processing of some conditions, all the contents see: Guide/topics/fundamentals.html#lcycles. Here, the thief is the first to seize the king, or to take the activity out as a model.



Continue to steal pictures from the SDK. A natural activity life journey, starting from OnCreate, to OnDestroy extinction. But the moon has a cloudy round missing components have the blessing overnight, when the system needs and components are located in the background, the process at any time may be recycled for the country, which makes it important to know what to cut into the background.
When the component enters the top of the stack and interacts with the user, it calls the Onresume function, similar to the OnPause function that is called when exiting the top of the stack. Onresume and OnPause can handle a lot of things, the most common is to do some files or set up the reading and writing work. Because, when the component is no longer in the foreground, other components may need to read and write the same file and settings, if it is no longer onresume to do the refresh work, it may be a dirty data (of course, the specific situation, but also need to be specific analysis, if the file is not read by the Bulls, Can be put into the oncreate to do reading work).
In addition to the foregoing in the background will be harassed by other components of the problem, in addition, the death of an indefinite cause is also a very scary thing. In Android, the components have two common methods of death, one is natural extinction, for example, the stack element ABC, into AB, C components will naturally die out. This kind of dead hair feather, do not need extra care. But another situation, is the system is recycled, it is the death of the heavy like Tarzan, for the motherland.
But the death of this way, for the user, more puzzling. Imagine, a game, you can not save, you have been playing AH play, three days and three nights did not sleep, this time you mm call to encourage, you energetic ready to redouble your efforts, but found that your game process, in the background, the system was recycled, one night back to the liberation of three days to become a bubble, You will not want to kill the game, will not be will not, will be. At this time, if there is no activity life cycle this thing, the game programmer must be deaths, became the android scapegoat. However, Android components have a life cycle, and if that happens, don't hesitate to kill the developers.
In order to escape, programmers have a piece of gold-free, that is the state mechanism of Android. State, which is a collection of serializable key-value pairs, is the developer who stores some of the current running status information in a bundle object. If the activity component is in a process that needs to be recycled, the Android core persists the bundle object on its activity component to disk, and when the user returns to the activity, the system reconstructs the component. And will persist the bundle object recovery to disk. With this persistent state information, developers can distinguish between specific dead-end methods and have the opportunity to restore back-of-life activity to a pre-death state. What developers should do is to use the Onsaveinstancestate function to maintain the state information (in the default state, the system control will save the relevant state information, such as TextView, will save the current text information, this does not require developers to worry about ... ), write to the bundle object, and then read and restore the relevant information in the Onrestoreinstancestate function (Oncreate,onstart, can also be processed ...). )。

Thread
Read data, background processing, these wretched buddies, naturally without thread participation. In the Android core scheduling level, is not to consider threading, it is concerned about only the process, each component of the construction and processing, are on the main thread of the process, so as to ensure that the logic is simple enough. Multithreading is often what developers need to do.
Android threads are also implemented by the Run method by deriving Java thread objects. But when users need to run a thread with a message loop, Android has better support, from handler and Looper. Handler does is to send and distribute the message, derive its handlemessage function, can handle a variety of received messages, and win development is the same. Looper's task is to construct loops, waiting for exits or other messages to come. In the Looper SDK page, there is a standard example of a message loop thread implementation, and, of course, a more standard approach might be to construct a handlerthread thread that passes its looper to handler.
In Android, the use of Content provider is often linked to threads, who make it relevant to data. As mentioned earlier, the content provider in order to maintain more flexibility, itself only provides the interface of synchronous invocation, and because asynchronous to the Content provider is a common operation, Android through Asyncqueryhandler object , an asynchronous interface is provided. This is a subclass of handler, and developers can invoke the Startxxx method to initiate an operation that, by deriving the Onxxxcomplete method, waits for the completed callback to complete the entire asynchronous invocation process, which is very simple and straightforward.

Implement
The core implementation of the entire task, process management, in the Activitymanagerservice. In the previous article, intent parsing, is the activitymanagerservice to be responsible for, in fact, it is a very misnomer class, because although the manager Service called activity, but its scope of jurisdiction, not only the activity , there are three other types of components, and the processes in which they are located.
In Activitymanagerservice, there are two types of data structures that are most striking, one ArrayList and the other HashMap. Activitymanagerservice has a large number of ArrayList, each component, will have multiple ArrayList to be stored in a state. Dispatch work, often is from a arraylist inside take out, find a way to tune a tune, and then throw to another ArrayList inside, when this component does not correspond to the ArrayList put, it is not far away from death. HashMap, because there are components need to use the name or intent information to do the positioning, such as content Provider, its search, is based on the URI, with the HashMap, everything is logical.
Activitymanagerservice uses a number of known Xxxrecord data structures to express the various surviving components. So there, Historyrecord (Save the activity information, the reason is called the history, is relative to the task stack) ... ), Servicerecord,broadcastrecord,contentproviderrecord,taskrecord,processrecord, and so on.
It is worth noting that Taskrecord, we have been saying that the concept of the task stack, in fact, the real bottom, and will not be in the Taskrecord, the maintenance of an activity stack. In Activitymanagerservice, the activity of each task is historyrecord in the form of a ArrayList, each Historyrecord, will hold a reference to the Taskrecord it resides in. When there is an activity, execution completes, and exits from the conceptual task stack, Android is done by scanning the same Taskrecord Historyrecord from the current Historyrecord location. This design makes a lot of seemingly logical and complex task systems in the upper layers, which are very unified and concise and commendable in their implementation.
Processrecord, which is the core of the entire process managed implementation, stores information about all components running on this process, according to which the system has a set of algorithms to resolve how to dispose of this process, if it is interested in the recycling algorithm, It can be seen from the trimapplications function of Activitymanagerservice.
For the developer, to understand this part of the implementation, mainly can help understand the whole process and the concept of the task, if the understanding of this piece is clear, you do not have to touch activitymanagerservice this monster.

Android tasks, processes, and threads

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.