Http://www.2cto.com/kf/201108/102108.html
What is the knowledge of the official API. However, since many people are not good at English, they have reproduced this article, and the translation is very good. Do not understand the activity declaration cycle, and the program framework design, it is best to take a look.
Activity and Task Design Abstract
Activity is the main component of Android applications.
In addition to writing the activity by yourself, you can also use intent to easily reuse the activity of other applications.
You can enable the activity in your application to be used by other applications through intent.
The system's activity stack can handle almost all the situations. However, in either case, you may need to set the flag or the like to determine the right thing happens.
In this document
Applications, activity, activity stack, and task
An example of activity and task
Start an activity from the main screen (start a new task and start the activity as the root activity)
Leave an activity
Reuse an activity (call an existing activity in the system to complete the task)
Replace the activity (use the new activity as the receiver of the default intent)
Multiple tasks
Start the application from two entry points (one application has multiple main launcher Activities)
Intent
Switch between tasks
Design Recommendations
If you do not want your activity to be reused, do not use intent filter.
Note that the intent cannot find the activity.
How to start the application
Allow the activity to be added to the current task.
Notification should make it easy for your users to leave
Use notification system
If it is not absolutely necessary, do not control the back key (that is, do not overwrite the onback () event of the activity)
Reference
Application Basics
This document describes the core principles of the Android Application Framework from a high-level, user-centric perspective. This is useful for interaction and Application designers and application developers.
This article uses multiple examples to illustrate the activity and task, and describes some of their underlying principles and mechanisms, such as navigation, multi-task, activity reuse, intent, and activity stack. The document also highlights some design conclusions you can use and how you control the UI of your application.
This document uses many Android applications as examples, including some default applications, such as Dialer and Google applications, such as maps. You can try them on your android simulator or Android phone. Note that your mobile phone may only provide some examples and applications in these documents.
Some principles, suggestions, and precautions will be mentioned in the design recommendations section. The basic application covers the underlying mechanism of the program. This document supplements and improves it.
Applications, activity, activity stack, and task
The following four basic concepts help you understand:
Application
Activitie
Activity Stack
Task
Application
A typical Android Application is composed of one or more related loosely coupled activities that users can interact. Typically, an application is packaged into a separate APK file. Android apps with a large ticket may include emails, calendars, browsers, maps, text messages, contacts, photos, dialing, playing music, setting, and so on.
The android main screen is generally the application initiator (launcher ). In general, it is a sliding drawer with many application icons (that is, under the default Android system, there will be a lot of icons when you drag your fingers up .), You can start the application from above.
Activity
Activity is the main component of Android applications. When you create an apllication, you can create your own activity or reuse another application activity to assemble the application. These activities are bound together at runtime, so newly installed applications can benefit from the installed activity. Once combined, these acitifiers work together as a whole. An activity has an independent visual UI, which should be based on an independent and clearly defined intent. For example, other user behaviors such as viewing images, editing, dialing, taking photos, searching, sending data, and voice commands.
An application that needs to be displayed on the interface must have at least one activity.
When an Android device is used, the user will jump from one interface to another, which should be smooth. Users should not be aware of underlying behaviors, such as switching between activities or tasks.
An activity holds a specific type of content (data) and receives a series of related user actions. In general, the lifecycle of each activity is irrelevant to other activities in the same application or task. Each activity is run independently. You or the system can start, run, pause, resume, stop, or restart the activity as needed. Due to this independent feature, there are many ways to override or reuse the activity.
The dialing program provided by Android is an example of an activity combination. This program is composed of four activities: Dialing, contact list, contact details, and creating a contact. As follows:
Below are some examples of other applications composed of multiple activities:
Email-view the directory, view the message list, view the message, write the message, and configure the account.
Calendar-view the day, week, month, and plan, edit the time, set attributes, and remind
Camera photography-run the camera, view the image list, view the image, cut the image, run the camera, watch the video list, and watch the video
Games-games themselves and installation settings
Map-view the current location, list (turn list or friend list), details (friend location, status, photo)
Activity is the most important of the four components that constitute the application. The other components are service, contentprovider, and broadcasereceiver. For more details about the activity, see the activity section in the application component.
Activity Stack
When a user jumps from one activity to another in the application, the android system saves the linear navigation history of a user accessing the activity. This is the activity stack, also known as the return stack (press the back key to return the activity stack ). Generally, when a user runs a new activity, the activity will be added to the activity stack. Therefore, when a user
When you press the back key, the previous activity in the stack will be displayed. You can press the back key until it is returned to the home screen. The adding of an activity to the current stack happens whether or not that activity begins a new task (as long as that task was started without going home ), so going back can let the user go back
To activities in previous tasks. The operation to add the activity to the current stack is irrelevant to whether the activity has started a new task. The return operation allows the user to return from the current task to the previous task. On the Application Manager, home screen, or "recent Task" screen, you can restore the task to the previous one.
Only the activity can be added to the activity stack. Others, including view, window, menu, or dialog, do not work. That is to say, assume that interface a jumps to interface B, and then the user can use back to jump back to interface. In this case, both A and B are implemented as activities. This rule has an exception. That is, unless your application controls the back key and manages the interface navigation.
Task
A task is a group of activities that you can complete for a specific target. It has nothing to do with the application that the activity belongs to (it seems that a task is a group of activities from the user's perspective, in order to complete a task ). Unless a new task is explicitly created (refer to interrupting the task), all activities started by the user are part of the current task by default. Note that these activities may belong to any application-belong to the same application or belong to different applications.
This means that a task can start from the contact list, select an email address (via email activity), and attach a photo (via image activity ). The contact list, email, and image are all stored in different activities (Task example ).
The activity that starts a task is called the root activity (the root activity also determines the attribute of the task ). Generally, a task starts from the Application Manager (Application List), the main screen (idle), or the most recent task (long press the Home Key) (describes when a task is created ). You can click the root activity icon to return to the task (press the Home Key and then click the root activity icon again on the home page), just like starting the activity.
In this task, the back key can return to the previous activity of this task. The activity stack can be composed of one or more tasks.
Examples of tasks:
Send an SMS with attachments
Watch YouTube and share the video via email
An important feature of interrupting a task is that a user can interrupt the current task (his task) and perform another task, then you can return to the original task to complete it. The intention of this feature is that you can run multiple tasks at the same time and switch between these tasks. There are two main ways to exit a task. In these two cases, the user should be able to return to the task they left:
The user is interrupted by the notification-a notification is sent, and the user starts to pay attention to processing the notification.
The user decides to start another task-the user presses the Home Key and then starts another application
Of course, there are always exceptions to rules. Apart from the two methods mentioned above, there is indeed a third method to start a new task, that is, when startactivity is in the code, define it to start a new task (that is, the flag of intent is new-task ). This is what map and browser applications do. For example, if you click an address in an email, the map activity will be called up in the new task, and a link will be clicked in the email to bring up the browser in the new task. In this case, the back key will return to the previous activity (email activity in another task) because it is not started from the main screen.
An example of activity and task
The following example illustrates the basic principles of application, activity, activity stack, back key, task, and intent. It shows how the system responds to user operations, including starting activity and switching between tasks. You can execute these examples on your Android phone as instructed below.
Start an activity from the main screen
The main screen is where most applications are started. (Some applications can only enter from other applications .) When a user clicks an icon in the Application Manager (or a shortcut on the main screen), the main activity of the application is started to the foreground and has the focus of the user. As shown in the following figure, the user enters the home screen and clicks the email icon to start the message list activity of the email application. The activity on the main screen is set to the background and stopped. When the user re-enters the main screen, restart.
In the activity navigation bar, use the back key and Home Key to exit the activity.
Whether an activity maintains its status depends on how the user leaves it-whether the activity is completed through the home or back key (the default operation of the back key is to finish the activity ).
By default, press the back key to finish (destroy) the current activity, and then display the previous activity to the user. In the figure below, you can click the email icon on the main screen to start the email application that displays the email message list. The user scrolls the list (changes the Initial State ). Click back to destroy the message list activity and return to the previous activity, that is, the main screen. After the user restarts the email application, the list displayed by the email application is reinitialized without scrolling.
In the above example, press back to return to the home screen because the home screen is the last activity that you can see. If the user enters the message list activity from another activity, press the back key to return.
As a comparison, the next chart shows the situation where the user leaves the message list activity with the Home Key instead of the back key-the message list activity will stop and move to the background without being destroyed. Restart the email application from the shortcut mode and set the background application to the foreground (from stop to running ). The rolling status will be the same as when the user leaves.
Exceptions. After some background activities return to the foreground, they enter their initial interface (rather than the status when they leave ). This is the activity of the Contact application and the Image view application. When the user enters the Contact application from the main screen, select a contact to view the details. (Then the home key ). If the user enters from the main screen again, the contact list will be returned instead of the details at the time of departure. In this way, the Contact application is designed because the contact list is the master entry point of the four tabs of the entire application.
In addition, not all activities will be destroyed when they are pressed back. When the user uses the music app to play the music and then press the back key, the app overwrites the behavior of the back operation. The activity is not destroyed, but is only invisible. (So the status is saved ). The music continues playing, and a notification is displayed, allowing you to return to the Music Activity to control the playing of the music. Note: you can write the activity that is destroyed when it is invisible, or the activity that will be switched to the background just like a music activity.
Reuse an activity
If activity a starts Activity B in another application, Activity B is reused. This happens when activity a broadcasts the query capability and B has this capability.
Contacts uses gallery to retrieve images. The contacts activity has a region to display the images of contacts. In general, all the images are stored in Gallery. Therefore, contacts can reuse gallery activity to retrieve images. This is a good example of reusing gallery activity. The following figure shows the process (main part ). The process is as follows: Click contacts, click a contact to View Details, press the menu key, edit the contact, and click the image area. Then the gallery activity is started. After finding the desired image, you can crop and save it. Saving this action will cause the image to be inserted into the image area of the contact details.
Gallery returns an image to start its own Contact application. The following example shows how to reuse an activity without returning it. Note that the following icon is a description of the activity navigation history (namely, the activity stack. You can press back until you return to the home screen.
When designing an application, it is a good idea to consider how to reuse the activity in other applications and how your activity can be reused by other applications. If your activity has the same intent filter as an existing activity, the system will provide you with a selection interface for these activities.
Gallery reuse messaging to share images-sharing is another good example of reusing activity in different applications. As shown in, when you start Gallery, select a graph, press the menu key, select share, and select messaging. This starts the messaging activity, creates a new message, and attaches the image to it. Then the user fills in the "recipient", writes a short message, and sends it. The user's focus is on the messaging program. To return to gallery, you must press the back key. (You can use the back key to return data from any activity to the home screen .)
Unlike the previous example, the reuse of messaging activity is not returned to the gallery activity that starts it.
The two examples show task-a series of activities to accomplish a target. In each example, an activity from different applications is used to complete the task.
Replace an activity
In this case, activity a replaces Activity B in different applications. This usually happens when activity a performs a job better than Activity B. In other words, the function of a is enough to replace B. Unlike reuse, A and B do different things.
In this example, the user downloads a substitute for the phoneringtone activity called ringsextended. Now, when the user enters setting, sounddisplay, and phoneringtone, the system will provide a selection interface, allowing the user to choose whether to use the phone bell activity of the Android system or the new one. In this dialog box, you can select "use this option by default ". The user selects ringsextended, and then the new activity is started, replacing the original Android system phone number activity.
Multiple tasks
As mentioned above, a user can switch from an activity to the home screen, and then enter another activity, but the previous activity will not be destroyed (there are two tasks at this time, namely, the task before the home, and the task that is restarted after the home ). The following shows how to enter the map application.
State 1-enter viewmap activity and search for an address. If the network is very slow, the application needs to search for exceptions for a long time.
State 2-the user wants to do other things while waiting, so he presses the Home Key and leaves map, but does not interrupt the network connection. Now map continues to work in the background.
Note: You can decide whether to continue running or stop the program after it is moved to the background. (Refer to onstop (), activity lifecycle ). For activities such as downloading data from the network, it is recommended that they continue working in the background. You can perform multiple tasks.
State 3-now, map activity is running in the background. The main screen is displayed at the front-end. Then, the user runs the calendar activity and sets the calendar to the foreground. Now you can focus on the calendar and view the calendar of today. (As shown in the middle crude line)
State 4-Press the Home Key and click map to return to map activity. The map is read.
The application initiator of the home screen starts two activities, viewmap and dayview, in two different tasks. At this time, the system is multi-task-running multiple tasks.
Launching from two entry points
Each application must have at least one entry point-so that the system or user can enter the application activity. In applicationlauncher on the main screen, each icon represents an entry point. The application can also be accessed from other applications. Each activity is a potential entry point of an application.
The phoneapplication provided by Android has two entry points: contact and dialer. A user in the contact can click a phone number to enter dialer. As shown in, you can click the contact icon to enter contactactivity, and then click a phone number to enter dialeractivity and call.
Once you enter the application, you can use tabs, menu items, list items, buttons, or other interface control elements to access other activities, such as newcontact or editcontact.
Intent
When a user wants to act on a certain type of data, for example, clicking a mailto: info@example.com link, they actually Initialize an intent object (an intent ). This intent will be resolved into a specific commp NENT. (Activitycomponent only ). (Translated into adult words: when a user wants to do one thing (at this time, the intent wants to do one thing), it will actually Initialize an intent, broadcast inquiry system, then, a specific activity is called .)
Then, the user clicks mailto: The result of the link, which is an intent object. The system will try to use this intent to match an activity. If the intent explicitly indicates an activity (a specific intent), the system immediately enters the activity to respond to the user action. However, if the intent does not name the activity (an unclear intent), the system compares the intent with the intentfilter of all available activities. If multiple activities can process this action and data, the system will allow the user to select one.
The following is an example of clicking mailto: link. If there are two applications on the device that process the email, when the user clicks the email address, a dialog box is displayed, asking the user to select one among the two applications. (Gmail and email ).
Here are some examples of intent objects and the activities they resolve to: Here are some examples of intent objects (not specific) and intent corresponding activities:
View the contact list-resolves to a contact list viewer Activity
View specific contacts-resolves to a contact viewer Activity
Edit a specific contact-resolves to a contact editor Activity
Send an email to a specific address-resolves to an email Activity
Call-resolves to A Phone Dialer Activity
View the image list-resolves to an image list viewer Activity
See figure-resolves to an image Viewer Activity
Crop an image-resolves to an image Cropper Activity
Note that the intent object specifies two things: behavior and data:
A behavior to be performed. In the above example, watching, editing, dialing, and cropping are all actions.
Specific data for such behavior. In the above example, the contact list, specific contact, phone number, graph list, and specific graph are all data.
Any intent that starts the activity on the main screen is a clear intent. In addition, some activities that enter their own application use clear intent.
For more information about intent, see intent class and intent filters.
Switch between tasks
The following figures show how users can convert between two tasks. In this example, the user writes a text message and attaches a picture to it. When doing these things, the user looks at the calendar. Then, the user comes back and continues to attach photos and send messages.
Start the first task. To send a message with an image appended, You need to perform the following operations:
The last step of the main screen> messaging> newmessage> menu> attach> pictures is to start gallery to take the photo. Note that gallery is in another application.
Before the user figures, the user decides to take a look at the calendar, which is another task. However, the current interface does not have a direct button to the calendar, so the user must go back to the main screen.
Start the second task. Press the Home Key> click calendar to view the calendar. Calendar is started as a new task. All applications started by applicationlauncher are new tasks.
Switch to the first task and complete it. After reading the calendar, the user presses the Home Key> messging and returns to continue appending the image. This operation does not enable the user to enter messaging, but to enter the gallery that has just left (even if these two are not an application !). Then, select an image, add it to the message, send the message, and complete the first task.
Design Recommendations
The following are suggestions and instructions for Application designers and developers.
When the activity you write does not want to be reused, do not write intentfilter. Use an accurate intent to call it.
When you do not want your activity to be reused by other applications, make sure that no intentfilter is defined on this activity. You can only access the activity from the application manager or from the same application. You should apply this method. For this type of activity, use a specific intent. (Instead of using intent to query system capabilities ). In this case, there is no need to use intentfilter. Intentfilter is released to all other applications. Therefore, if you use intentfilter, you are actually adding an external portal to your activity, which may cause unintentional security vulnerabilities.
When you reuse the activities of other applications, do not forget to deal with situations where no activity meets the requirements.
Your application can reuse other activities if they can be reused. During reuse, you cannot assume that your intent will be able to match an external activity. You must consider that there is no suitable activity.
You can test whether there is a match before starting the activity, or you can start the activity directly and handle the exception. For two solutions, see blog can I use this intent ?.
By querying packagemanager, you can know whether an intent can be matched with an activity. The blog provides an example in the isintentavailable () method. Then, if they do not match, you can stop constructing intent objects, or remind the user of an address, such as market, to download the desired application. In this way, when your code calls startactivity () or startactivityforresult (), you can ensure that the intent object is tested and can match the appropriate activity.
Consider how your activity can be reused by other applications.
A designer or developer should know how users can start your application and use the activity in the application. You can use the activity in your application through the main screen or other applications.
Start your main activity from the main screen-if your application can run independently, the user may use applicationlauncher (usually implemented as a slide drawer on the main screen) or shortcuts on the main screen, or taskswitcher to start it. (This mechanism is used for intentfilter. The main category is the launcher activity .)
Start your activity in other applications-maybe your activity can be reused. For example, many applications can share data with other users. You can share data by email, text, or uploading data to a public website.
When one or more of your activities can replace an existing activity of another application, you can make your activity available to the user when the user needs this activity. For example, if your activity can also send data (email, text, or upload), consider providing your activity as an option for users. A specific example is provided. Gallery allows users to share images. When a user selects "share" from the menu, the system compares the "share" Request (an intent object) and the available activity (through their intentfilter), and then provides it to the user for selection.
The system matches email, Gmail, messaging, and Picassa. If your activity can also send images or upload images, you only need to configure intentfilter to make your activity available.
When other activities start your activity, they may expect or do not expect a return.
Expected Return-this is a closed loop. The started activity must return a definite value or be canceled. In the example of sharing images from gallery above, after the user completes the sending or uploading operation, the user returns to gallery. This is an example of enabling an external activity in Gallery. (This is the case with startactivityforresult ).
It is not expected that a response is returned-in this case, it is open. Taking clicking an address in the email as an example, mapactivity is started to display the map. The email does not need map to return anything. You can press back to return. (This is the case with startactivity ).
Your activity can only be started from other applications. -In the previous example of sharing images via email, Gmail, messaging, or picass, all activities can be started by clicking the icon on applicationlauncher on the home screen. The activity used to crop an image and append a file cannot be started from the main screen. They need a context runtime environment and cannot run independently.
In fact, not all applications have icons and can be started on the main screen. Take a small application that is not commonly used as an example. This small application can replace the entry point function in other applications. For example, Android generally has a built-in ringtone selector, which allows you to set the sound settings in the app. You can write your own ringtone selector, which can be entered using the same intent as the system selector. As shown in, when you select "phone number", a dialog box is displayed, asking the user to choose whether to use the system selector or your selector. the user can save their selection. The ringtone selector is rarely used and has a clearly defined start point (in other applications ). Therefore, there is no need to create a separate icon on the home screen.
One application has two or more main activities, and these main activities have icons on the main screen. -We have defined that everything in the single APK file belongs to an application. You can write an application with multiple main activities.
Camera.apk is a good example of multiple separated main activities of an application. It has two main activities, camera and camcorder, which have different icons and can be accessed independently. In the user's opinion, it seems that there are two different applications. They share the same lens and store data (static or dynamic images) in Gallery.
In order for your application to contain two different, independent activities launchable from home, you must define them to be associated with different tasks. if you want your applications to include two unrelated activities that can enter from the main screen, you need to define them to be associated with different tasks. (This means that different taskaffinity values must be set for each main activity. In the preceding example, "com. Android. Camera" and "com. Android. videocamera" are used ".)
This is also the case with contacts and dialer. In the two main activities of the same application.
Make your application a widget-An application can also display its own part as an appwidget, embed it into the main screen, or other applications, and periodically receive updates.
Allow your activity to enter the current task. (Instead of creating a new task ).
If your activity can be started by other applications, you should allow them to enter the current task, or an existing task with taskaffinity. This allows you to add an activity to a task. You can switch between tasks that contain your activity and other tasks. Unless your activity only allows one instance.
To achieve this effect, the launchmode of your activity should be standard or singletop, rather than singletask or singleinstance. These launchmode (standard or singletop) Allow your activity to have multiple instances.
Notification should allow users to easily return the previous activity.
Applications running in the background can use a service to send notifications to users so that they can know the events they are interested in. Calendar and email are two examples. Calendar sends a notification as the alert, while an email sends a notification to remind the user of a new email. We recommend that you return to activitya when you receive a notification, enter activityb through this notification, and then press back.
The following process shows how activitystack works when a user processes a notification.
Create a new reminder event in the calendar, and then find that you need to copy some content from an email.
Click Home> Gmail.
In Gmail, the user receives a notification from the calendar, reminding him that he is about to have a meeting.
The user selects this notification, so the user enters another calendaractivity, which displays the detailed summary of the meeting.
The user selects this reminder and wants to see more details.
After reading this event, press back. Back to Gmail, where he just left to see the notification.
These actions are not mandatory.
Notification is generally implemented in one of the following ways:
The displayed activity only serves the notification service. -For example, if you receive a notification from the calendar, selecting this notification will start a special activity. This activity shows a list of upcoming events-this view is only used to display notifications, and there is no entry in the calendar UI. After reading the list of recent events, make sure that you can return to the activity he just clicked notification with the back key. Make sure that the taskaffinity of this dedicated activity is different from that of calendar Ar or any other activity.
(To Do This, set taskaffinity to an empty string to indicate that the activity is irrelevant to any other task ). The following is an explanation.
Because of the task's working method, if the taskaffinity of this dedicated activity remains the default value, after you press the back key in step 1 above, the task will return to the calendar instead of Gmail. By default, all the activities of the same application have the same taskaffinity. Therefore, the taskaffinity of this dedicated activity matches the calendar task in step 1. This means that if you select notification, the existing calendar event (the one in step 1) will be pulled to the front, and then the dedicated activity will be put to the top.
This is not what you want. Set taskaffinity of this dedicated activity to an empty string to correct this problem.
The displayed activity is not dedicated, but the initialization status is displayed on the foreground. -For example, when Gmail arrives at the frontend in response to notification, it always displays the session List. You can put the "clear top" flag in the notification trigger intent to ensure this. In this way, when an activity is started, the activity always displays the initialization status, which prevents the Gmail from entering the foreground from being in the status when the user leaves. (You can put flag_activity_clear_top In the intent passed to startactivity () to do this ).
Other methods can also be used to process notification, including pulling activity to the foreground and displaying specific data (displaying the text message thread that just received the new message)
A notification always starts an activity to a new task. (Intent always carries flag_activity_new_task ). This is because an interruption to the current task should not belong to the current task.
Use the notification system-do not use diaolog instead of notification.
If your background service needs to notify users of anything, use the standard notification system-do not use dialog or toast for notification. The dialog or toast will immediately attract the user's attention and interrupt the user and divert his attention from what he is doing: The user may be inputting text. If dialog appears, these texts are suddenly applied to the dialog. Users are used to processing your messages and notifications at convenience.
If not absolutely necessary, do not take over the back key.
When a user moves from one activity to another, the system puts them in the activity stack. These are used by the back key in the form of a navigation history. Most activities have limited purposes and have a single series of data, such as reading a batch of contacts, writing emails, or taking photos. However, if your application is just a large activity with some pages, what if you need to control the back key in Fine Granularity? Examples of such applications are browsers and maps. Google has a series of web pages, and Google Maps have a series of layers to switch.
Both applications take over the back key and have an internal return stack.
For example, map uses the layer to display different information on the map to the user: display the address search result, display the address of a friend, and display the route between two points. Map stores the stack of the layer, so the back key can return to the previous layer.
Similarly, browser uses a browser window to display different web pages. Each window has its own navigation history, similar to the tab of the browser in the desktop operating system. Each tab has a different return stack. For example, if you did a Google Web search in one window of the android browser, clicking on a link in the search results displays a web page in that same window, and then pressing
Back wocould to the search results page. pressing back goes to a previous window only if the current window was launched from that previous window. if the user keeps pressing back, they will eventually leave the browser activity and return home.