Android basics 05: Activity 02 of four major components

Source: Internet
Author: User
Tags home screen

This series begins to introduce the four main components of the activity, mainly to sort out relevant information about this part on the network. It contains the following three articles:

Android basics 05: four major components activity 01: Basic knowledge

Android basics 05: four major components activity 02: Activity and task

Android basics 05: four major components activity 03: startup mode instance

This section describes the relationship between an activity and a task.

The full text is based on the blog "design ideas and methods for activity and task".

Activity and task are the most basic applications in the Android Application Framework architecture. Developers must understand their usage and development skills. This article uses a large amount of space and uses examples to explain their basic principles (underlying principles) and Architecture (Mechanisms) Step by step. For example: navigation, multitasking, activity re-use, intents, and activity stack... Most of its application modules. Focuses on how to more accurately reflect the convenience and efficiency of user interaction in the development process, and also helps analyze
Problems faced by developers during development.
Some of the examples involved in this article are the applications that come with the Platform (such as dialup programs), and some representative applications in the Google product line (such as Google map ). We recommend that you use emulator or Android-powered device to test the effect of the Instance. This helps you better understand the meaning of some modules. (Note: The hardware may not support certain functions, so some instances may not be able to be browsed on your test machine)

First, you need to understand some basic modules:
Applications
Acitivities
Activity Stack
Tasks
The above four modules are very important for understanding this article. Next we will briefly introduce their meanings and usage one by one (you can also directly view the official documentation through its link ).

Applications
Any Android Application is basically composed of some activities. When a user interacts with an application, some of the activities it contains have close logical relationships, or each of them processes different responses independently. These activities are bundled together into an application that handles specific requirements, and the extension named "pai.apk" is included in the file system. Apps on the Android platform, such as email, calendar, browser, maps, text message, contacts, camera, and dialer, are independent APPs by default.
Activities
As mentioned above, activities are the main component of applications. In fact, it can be more specifically understood that application is just an abstract label, which associates some activities in the system, collaborate to fulfill specific user needs. The Installation Process of the application can also be simply understood as importing the wrapped activities to the current system. If the same activities already exists in the system, it will be automatically associated, the same activities will not be installed repeatedly to avoid resource waste. When the application is uninstalled, the associated
Whether activities are associated with other application labels. If you only provide the current application, activities will be completely removed. Otherwise, no operation will be performed.
Most of the interactions between users and applications are completed through the GUI. On the Android platform, you can define the GUI in two ways. XML can be used to preset static GUI elements, you can also dynamically define GUI elements in the activity class. These two methods are driven by activity and respond to user interaction events. After the application is started, at least one activity instance containing GUI information must be created.
The activity body consists of two main parts: content (data) and response to user interaction events. List a dialer example, which includes four parts: The Dialer main interface, Address Book, viewing contact information, and adding new contacts.

The following lists more representative applications and their activities:
Email-activities to view folders, View list of messages, view a message, compose a message, and set up an account
Calendar-activities to view day, view week, view month, view agenda, edit an event, Edit Preferences, and view an alert
Camera-activities for running the camera, viewing the list of pictures, viewing a picture, cropping a picture, running the camcorder, viewing the list of movies, and viewing a movie
Game-one activity to play the game, typically another for setup
Maps-one activity to view a location on a map, a second for lists (such as turn list or friend list), and a third for details (friend location, status, photo)
The application is basically composed of four modules: Activity, service, content provider, and broadcast receiver. activity is the main body of the application.
Activity Stack
When operating applications, you sometimes need to call multiple activities to fulfill the requirements. For example, to send an email program, first enter the main interface of the email, and then start a new activity to enter the content of the new email, you can also call up the contact list to insert Recipient Information. During this operation, the Android platform has a mechanism dedicated to managing the activities stack, which can easily record activities instances linearly. When an operation is completed, you can use this navigation function to return the previous activity (by "back" of the console ").
Each time a new activity is started, it is added to the activity stack. You can easily return the previous activity to the home screen. After arriving at the home screen, you will no longer be able to view the stack record (as the saying goes: androidres.com ). If the current task is aborted (interrupting the task), other operations are started after it is returned to the main interface of the system. If you want to return to the previous Task for further execution, you only need to start the root activity of the task through the application launcher or shortcut on the main interface again to return the status of the task during suspension and continue the execution.
Compared with views, windows, menus, and dialogs, Activity is the only data that can be recorded in the history stack, therefore, when the application you designed requires the user to enter the next-level interface B from interface A, and the user needs to return a again after the operation is completed, a must be considered as the activity, otherwise, it cannot be returned from the history stack.
Tasks
On the Android platform, tasks can be understood as multiple activities working together to complete an application, regardless of the specific application of activities. The following figure shows the relationships among applications, tasks, and activities (provided by androidres.com ):

Activities can be viewed as independent systems resources and as the subject for implementing specific applications. Tasks associate activities to implement a more complex application, A single task or multiple tasks can be defined as an application.
A root activity usually exists in a task, but not in all cases. You can use the shortcut of application launcher and home screen or by "Recent tasks" (hold down the home key for a long time) start in recently used task records. When another activity is started from an activity, the back key is used to return the previous activity, and the newly opened activity is added to the activity stack.
Here are two examples represented as tasks:
Send emails with attachments
View YouTube videos and share them with other contacts by email.
-Interrupting the task
This is a very important feature of a task. You can abort a completed task in real time and start a different task. After the new task completes the operation, you can still return to the task on which the task is terminated to continue the remaining operations. This feature greatly facilitates running multiple tasks at the same time and facilitates switching between them. There are two ways to jump from the current task to another task (both ways of switching the task can be returned to the status before the task is initially aborted ).
The system throws a notification. The current task is terminated and jumps to the notification task.
User force stop
Of course, in addition to the two methods, there is another special case. The third method is to start a new task: the activity itself is defined as a task. For example, maps and browser are application in the third case. You can use an address in the email to start the maps activity as a new task, or, start browser through the link in the email to start a new task. In this case, when the back button is triggered, it will return to the previous task (email ), because these new tasks are not started through application launcher or shortcut in home screen.
Understand the basic principles of activities and tasks
Please first understand the content mentioned above. If you are still confused about some concepts, please read more information in time (the official document is the best learning material ), otherwise, you will not be able to quickly understand the examples to be discussed next, or even lose your interest in reading.
Next, we will learn the basic principles of applications, activities, activities stack, tasks, intent, and other modules through some representative instances. Analyze the system's response principles to users in different modes from various perspectives.
Start an activity from home
Most applications are started from this (some applications are started through other applications ). There are two specific methods: one is to start from the system's application launcher, and the other is to directly use the home screen shortcut. After the application is started, the root activity is displayed in the current window and can be directly used to operate interface elements. The official website provides an illustration of this process. In fact, I feel that this description is not intuitive enough to use it together. The general process is to start the email application at home. In this application, the list operation can be directly provided to the user.
Messages activity and home activity switch to the background for running.

The difference between leaving the current activity using the back or home key
Both the application back and home can leave the current activity (Application-based root activity), and the home activity switches back to foreground. However, the most fundamental difference between the two is whether the user needs to retain the state of the current activity.
-Back:
Destroy will terminate the currently running activity and return it to the previous activity (if it is a root activity, it will be directly returned to the home activity ). The official website provides an illustration of the related process. When a user is operating on the list messages activity, the drop-down list of emails (which changes the scrolling status) will be returned to the home activity through the back key, when list messages activity is started through email icon again, the list is in the initial position. Through this demonstration, we can understand that when the current activity is left by the back key, its state data cannot be temporarily retained. When it is started again, it is equivalent to re-creating an instance.

Home:
If you use home to replace the return method of back, the current activity will be switched to background instead of destroied. In this way, the state information of the activity can be temporarily retained. When the activity is started again through application launcher or quick start, the status of the Last Exit can be returned. Compared with the example referenced in back, when the returned result is returned from home to activity again, the scroll status recorded in the last operation is displayed, instead of the default initial position.

Exception)
The front side lists two typical cases, and there are some exceptions. Some activities from the background being "summoned" to foreground are still equivalent to re-creating a new instance, it is different from the result described by the front. Even if it is temporarily stored in the background mode (not destroied), its state data will be lost. For example, contacts and gallery. When you start the Contact application and click an entry to view details, what you see is not the detailed information of a specific entry that you opened previously, but the initial default Interface. This example shows that the State information of the current activity can not be saved in all cases after the return using the Home key.
The other is a special case related to the back key. When the front side mentions that most of the activities are returned to the home activity through the back key, the activity itself will be completely destroyed. By default, the method for the activity to respond to the back button is defined by destroy. However, in some special cases, developers can "Override" the corresponding back button event as needed to cancel the default destroy action. The music player is a typical application related to it. When a user triggers the back button in the player's root activity, the user switches to the background mode to continue playing the current music.
Convert activity to foreground.
Activity Reuse
In multiple different applications, when an application with the same purpose is encountered, the reuse of the activity is involved, which is a very common situation in the development process. Reusability has been emphasized by many development institutions as the most effective mechanism to save costs and optimize resources. For the mobile application platform, the optimal utilization of resources is more important, and reusable applications are everywhere on the Android platform. Two basic examples are provided to illustrate the situation.
-Contacts uses gallery to obtain image resources
As we all know, contacts is the most common application on mobile phones. It is mainly used to store the contact information of the current user, which must contain the profile information of the contact. The image information on the Android platform is managed by gallery. Therefore, contacts must reuse the gallery activity to obtain the corresponding image information.
Applications developed for Android or other platforms must have a good sense of reusability, Which is required throughout the entire development process of the project. This includes how to use the existing resources of the current system, or considering that other applications may be used to meet specific requirements in the future. When the intent filter being called is not unique, a dialog box is displayed for the user to choose. This is indeed a perfect solution.

Extended gallery sharing using messaging
You can use gallery to view image resources in the current system. Each time you open an image resource, you can use menu-> share to insert the current resource as an attachment to the newly created messaging, and share the message to the recipient as normal. If you cancel the current sharing behavior, you only need to press back to return to the gallery activity. Compared with the previous example, message activity does not return any information after sending or canceling the message activity.

The above two examples illustrate how to use a series of activities to fulfill a certain requirement, and both of them call external application resources.
Replacing an activity
Currently, we want to introduce activities with the same intent filter attribute in different applications, which is not easy to understand for users who are used to operating systems such as Windows. In fact, if you are careful enough, you can find the information mentioned here in the previous example.
Generally, in this case, the external activity a with the same function is superior to the default action Activity B in the current application in terms of the ability to handle the problem, the system will throw a dialog box for you to select the optimal method for processing the current task based on subjective judgment. The entire process is illustrated through an easy-to-understand instance. It is recommended that the "hands-on ability" personnel can try it through the simulator.
For example, you have loaded the latest phone ringtone activity in the current system and named it rings extended. If you use setting-> sounds & Display-> phone ringtone to set the current ringtone attribute, an app containing the default phone ringtone activity and the latest loaded rings extended will pop up, in addition, the dialog box also provides an option to directly start the default system operation. If you select rings extended, it will be loaded into the current thread to replace the original default operation behavior, which can be enhanced according to the following illustration.

Multi-task concurrent running (multitasking)
In the previous sections, we mentioned the difference between home and back methods for switching to home screen and between them, this section focuses on the tasks that the system can process in real time at the same time. If you switch back to home activity by pressing the Home button while application a is in the Enabled state, and keep the status information of application a before running, you can enable the new program at the same time, you can also switch application a back to foreground.
Next, we will learn more about the process covered by map application through an instance.
The initial phase consists of three steps,
Step 1: Start the map application by application launcher and search for a specific geographic location. Assuming that the current network environment is not ideal, it takes some time to download map data.
Step 2: when the system needs to load the current map information data for a long time, keep the current activity status, return home activity to start other applicaton, and switch the map activity to background, the loading progress is not interrupted (the network connection is still maintained ).
Note: The above is the response behavior of the activity under the default conditions. After switching to the background status, the onstop () event is directly triggered. developers can redefine the method. For example, force the activity to terminate the network connection in the background state.
Step 3: The current map activity has been switched to the background state and the home activity has been switched to foreground. At this time, the user starts the calender activity, which will be automatically converted to the foreground status, and get the operation focus.
The preceding three steps are illustrated as follows:

Finally, exit the current calender activity and return to home. Use the maps icon again to switch the instance in the background status to foreground.

The preceding example shows that the system has a multi-task processing mechanism-running multiple tasks.
Two different ways to start Application
Each app must provide at least one entry point (which is a bit awkward to translate into an "entry point" and simply keeps it as it is) for users or systems to call the associated activities, the small icon in application launcher is the entry point of each independent app. In addition, the app can also start each other through activity as the entry point, and each activity contained in the app can be viewed as a potential entry point.
The phone application in the system also has two entry points: contacts and dialer. The following figure shows that the user starts the contacts activity through application launcher, selects a contact, and CALLS dialer activity to call the provided phone number.

Intents
In the real world, everyone will interact with the surrounding environment every moment. In this interaction process, we must first determine a kind of consciousness, such as feeling thirsty and needing to be supplemented with water. This kind of consciousness will guide you to solve thirst problems in a habitual way. There are many ways to use it, such as eating ice cream, drinking water, and chewing leaves. Similar to thirsty ideology, which is abstracted as intent and viewed as an object, Android responds to consciousness.
On the Android platform, users' operation behaviors are composed of various events. The system abstracts each event as an intent object to find a specific solution to this requirement. Abstract intent objects can be in two forms. The first is an explicit intent (explicit intent), which is associated with a specific activity during initialization. The second is the "ambiguous" intent (implicit intent), which indicates that the intent is not explicitly associated with the activity. When it is thrown, among the various activities, the system finds matching processing methods based on the intent filter. If multiple results exist, you can select an appropriate processing method as needed.
Referencing a specific example, after clicking a mailto: info@androidres.com link, the thrown intent belongs to the implicit intent, and the system captures the result for resolving this intent, select all the results (Gmail or email ):

The following shows the default intent Association list for more systems:
View the list of contacts-resolves to a contact list viewer Activity
View A participant contact-resolves to a contact viewer Activity
Edit a particle contact-resolves to a contact editor Activity
Send to a special email-resolves to an email Activity
Dial a phone number-resolves to A Phone Dialer Activity
View the list of images-resolves to an image list viewer Activity
View a particle image-resolves to an image Viewer Activity
Crop a particle image-resolves to an image Cropper Activity
The intent object contains two elements:
1) Action: such as viewing, editing, dialing, and viewing image resources.
2) data: Specific data provided for a certain behavior. Fruit must be provided for juice beverage processing (excluding the black heart store ).
Refer to the official website for explanation: intent class and intent filters.
Task Switching
The switching process is still explained by the application instance. In this example, the user edits a short message and inserts an image attachment, but starts the calendar before sending the message, switches back to the short message editing page, and finally sends the message.
1) start the first task: messaging app, Home> messaging> new message> menu> attach> picture. To insert an image, you need to call gallery activity, which is an independent external program.

Next, start another task. Because calendar is not directly run from the current activity, you need to switch to home.
2) start another application (calendar): Home> calendar

3) after viewing the calendar, switch messaging from background to foreground mode, including adding attachments and finally sending messages.

Now, the introduction of activities and tasks, two core elements of the Android platform, has come to an end. We may have more discussions about this in the future and hope to get your attention. In addition, some friends may have read the official original text, and this site is again lucky to have your read-through. If there are omissions or misunderstandings in some concepts or discussions, we sincerely hope to receive correction and help.

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.