Activity and Task Design Guidelines

来源:互联网 发布:重生之数据人生 编辑:程序博客网 时间:2024/06/05 02:24

Design Tips

The following are tips and guidelines for application designersand developers.

When writing an activity thatwon't be re-used, don't specify intent filters — use explicitintents

If you're writing an activity that you don't want otheractivities to use, be sure not to add any intent filters to thatactivity. This applies to an activity that will be launched onlyfrom the application launcher or from other activities inside yourapplication. Instead, just create intents specifying the explicitcomponent to launch — that is, explicit intents. In this case,there's just no need for intent filters. Intent filters arepublished to all other applications, so if you make an intentfilter, what you're doing is publishing access to your activity,which means you can cause unintentional security holes.

When reusing an activity owned by others,handle the case where no activity matches

Your applications can re-use activities made available fromother applications. In doing so, you cannot presume your intentwill always be resolved to a matching external activity — you musthandle the case where no application installed on the device canhandle the intent.

You can either test that an activity matches the intent, whichyou can do before starting the activity, or catch an exception ifstarting the activity fails. Both approaches are described in theblog postingCan I use this Intent?.

To test whether an intent can be resolved, your code can querythe package manager. The blog post provides an example in theisIntentAvailable() helper method. You can perform this test wheninitializing the user interface. For instance, you could disablethe user control that initiates the Intent object, or display amessage to the user that lets them go to a location, such as theMarket, to download its application. In this way, your code canstart the activity (using either startActivity() orstartActivityForResult()) only if the intent has tested to resolveto an activity that is actually present.

Consider how you want youractivities to be launched or used by other applications

As a designer or developer, it's up to you to determine howusers start your application and the activities in it. As anapplication is a set of activities, the user can start theseactivities from Home or from another application.

  • Launch your main activity from an icon at Home - If yourapplication can run standalone, it should probably be started bythe user touching an icon inapplication launcher(typically implemented as a sliding drawer on the Home screen), orfrom a shortcut icon on the Home screen, or from the task switcher.(The mechanism for this is for the activity to have anintent filter with action MAIN andcategory LAUNCHER.)
  • Launch your activity from within another application -Perhaps your activities are meant for re-use. For example, manyapplications have data they want to share with other users.Activities that can share data with other users include email, textmessaging and uploading to a public website.

    If one or more of your activities can be an alternative to anexisting activity in another application, you can make it availableto users at the point they request thatactivity. For example, if your activity can senddata to others (such as by email, text messaging, or uploading),consider setting up that activity to appear as a choice to theuser. To give a specific example, Gallery enables a user to viewand share pictures. When the user chooses "Share" from the menus,the system compares the "Share" request (an Intent object) toavailable activities (by looking at their intent filters) anddisplays choices to share. In this case, it matches Email, Gmail,Messaging and Picasa. If your activity can send a picture or uploadit to a website, all it needs to do is make itself available forsharing (by setting its intent filter).

    Another activity can start your activity either with or withoutexpecting a result back. 

    • Start an activity expecting a result - This approach isclosed loop, where the activity being started must either return avalid result or be canceled. In the previous examples of sharing aphoto from a Gallery, the user ends up back in the Gallery aftercompleting the send or upload procedure. These are examples ofstarting an activity external to the Gallery. (Such an activity isstarted withstartActivityForResult().)
    • Start an activity not expecting a result - This approachis open-ended. An example is choosing an house address in an emailmessage (or web page), where the Maps activity is started to mapthe location. No result from maps is expected to be returned to theemail message; the user can return by pressing the BACK key. (Suchan activity is started withstartActivity().)
  • Launch your activity only from within anotherapplication - The previous cases of sharing by way of Email,Gmail, Messaging and Picasa (from within Gallery) are allactivities that can also be started from icons in the applicationlauncher at Home. In contrast, the activities for cropping apicture and attaching a file cannot be started from Home, becausethey do not stand alone and require acontext. 
  • In fact, not all applications have icons and can be started fromHome. Take for example a small app that is infrequently used andreplaces existing functionality, that already has a natural entrypoint inside an existing application. For example, an Android phonetypically has a built-in ringtone picker that can be selected fromthe sound settings of the Settings application. A custom ringtonepicker application that you write could be launched by an intentidentical to the built-in ringtone picker. At the point where theuser chooses "Phone ringtone", they are presented with a dialogletting them choose between "Android System" and your ringtonepicker (and letting them save their choice) as shown in thefollowing figure. A ringtone is something you set infrequently, andalready has a well-defined starting point, so probably does notneed an application icon at Home.

    Activity <wbr>and <wbr>Task <wbr>Design <wbr>Guidelines

  • Launch two or more main activities within a singleapplication from separate icon at Home - As we have defined it,all the code in a single .apk file is considered to be oneapplication. You can write an application that containstwo main activities launchable from Home.
  • The Camera.apk application is a good example of an applicationthat contains two independent main activities — Camera andCamcorder — that each have their own icons in application launcher,that can be launched separately, and so appear to the user asseparate applications. They both share use of the same lens, andboth store their images (still and moving) in theGallery. 

    In order for your application to contain two different,independent activities launchable from Home, you must define themto be associated with different tasks. (This means setting the mainactivity for each task to a different task affinity — in this case,"com.android.camera" and "com.android.videocamera".)

    Contacts and Dialer are another example of two main activitieslaunchable from Home that reside in the same application.

  • Making your application available as a widget - Anapplication can also display a portion of itself as anapp widget, embedded in Home or anotherapplication, and receive periodic updates.

Allow your activities to beadded to the current task

If your activities can be started from another application,allow them to be added to the currenttask (or an existing task it has an affinitywith). Having activities added to a task enables the user to switchbetween a task that contains your activities and other tasks.Exceptions are your activities that have only oneinstance. 

For this behavior, your activity should have a launch mode ofstandard or singleTop rather than singleTask or singleInstance.These modes also enable multiple instances of your activity to berun.

Notifications should let theuser easily get back to the previous activity

Applications that are in the background or not running can haveservices that send out notifications to the user letting them knowabout events of interest. Two examples are Calendar, which can sendout notifications of upcoming events, and Email, which can send outnotifications when new messages arrive. One of the user interfaceguidelines is that when the user is in activity A, gets anotification for activity B and picks that notification, when theypress the BACK key, they should go back to activityA. 

The following scenario shows how the activity stack should workwhen the user responds to a notification.

  1. User is creating a new event in Calendar. They realize theyneed to copy part of an email message into this event
  2. The user chooses Home > Gmail
  3. While in Gmail, they receive a notification from Calendar foran upcoming meeting
  4. So they choose that notification, which takes them to adedicated Calendar activity that displays brief details of theupcoming meeting
  5. The user chooses this short notice to view further details
  6. When done viewing the event, the user presses the BACK key.They should be taken to Gmail, which is where they were when theytook the notification

This behavior doesn't necessarily happen by default.

Notifications generally happen primarily in one of two ways:

  • The chosen activity is dedicated for notification only -For example, when the user receives a Calendar notification,choosing that notification starts a special activity that displaysa list of upcoming calendar events — this view is available onlyfrom the notification, not through the Calendar's own userinterface. After viewing this upcoming event, to ensure that theuser pressing the BACK key will return to the activity the user wasin when they picked the notification, you would make sure thisdedicated activity does not have the same task affinity as theCalendar or any other activity. (You do this by setting taskaffinity to the empty string, which means it has no affinity toanything.) The explanation for this follows.

    Because of the way tasks work, if the taskAffinity of thededicated activity is kept as its default, then pressing the BACKkey (in step 6, above) would go to Calendar, rather than Gmail. Thereason is that, by default, all activities in a given applicationhave the same task affinity. Therefore, the task affinity of thededicated activity matches the Calendar task, which is alreadyrunning in step 1. This means in step 4, choosing the notificationbrings the existing Calendar event (in step 1) forward and startsthe dedicated activity on top of it. This is not what you want tohave happen. Setting the dedicated activity's taskAffinity to emptystring fixes this.

  • The chosen activity is not dedicated, but always comes tothe foreground in its initial state - For example, in responseto a notification, when the Gmail application comes to theforeground, it always presents the list of conversations. You canensure this happens by setting a "clear top" flag in the intentthat the notification triggers. This ensures that when the activityis launched, it displays its initial activity, preventing Gmailfrom coming to the foreground in whatever state the user lasthappened to be viewing it. (To do this, you put FLAG_ACTIVITY_CLEAR_TOP in the intent you pass tostartActivity()).

There are other ways to handle notifications, such as bringingthe activity to the foreground, set to display specific data, suchas displaying the text message thread for the person who just senta new text message.

A notification always starts an activity as a new task (that is,it puts FLAG_ACTIVITY_NEW_TASK in the intentit passes to startActivity()). This is done because interruptionsto a task should not become part of that task.

Use the notification system — don'tuse dialog boxes in place of notifications

If your background service needs to notify a user, use thestandard notification system — don't use a dialog or toast tonotify them. A dialog or toast would immediately take focus andinterrupt the user, taking focus away from what they were doing:the user could be in the middle of typing text the moment thedialog appears and could accidentally act on the dialog. Users areused to dealing with notifications and can pull down thenotification shade at their convenience to respond to yourmessage.

Don't take over the BACK key unlessyou absolutely need to

As a user navigates from one activity to the next, the systemadds them to the activity stack. This forms a navigation historythat is accessible with the BACK key. Most activities arerelatively limited in scope, with just one set of data, such asviewing a list of contacts, composing an email, or taking a photo.But what if your application is one big activity with several pagesof content and needs finer-grained control of the BACK key?Examples of such Google applications are the Browser, which canhave several web pages open at once, and Maps, which can haveseveral layers of geographic data to switch between. Both of theseapplications take control of the BACK key and maintain their owninternal back stacks that operate only when these applications havefocus.

For example, Maps uses layers to present differentinformation on a map to the user: displaying the location of asearch result, displaying locations of friends, and displaying aline for a street path providing direction between points. Mapsstores these layers in its own history so the BACK key can returnto a previous layer.

Similarly, Browser uses browser windows to presentdifferent web pages to the user. Each window has its own navigationhistory, equivalent to tabs in a browser in a desktop operatingsystem (such as Windows, Macintosh or Linux). For example, if youdid a Google web search in one window of the Android Browser,clicking on a link in the search results displays a web page inthat same window, and then pressing BACK would to the searchresults page. Pressing BACK goes to a previous window only if thecurrent window was launched from that previous window. If the userkeeps pressing back, they will eventually leave the browseractivity and return Home.

0 0
原创粉丝点击