Ch3. CreatingApplication & Activities Browny 06, May, 2011
Application Building Blocks(1/5)• Activities ‣ Ac#vi#es use Views to form graphical user interfaces that display informa#on and response to user ac#ons ‣ 例：一個 Email 程式，可能包含三個 ac#vi#es (1) 郵件列表的ac#vity (2)顯示郵件內容的ac#vity (3) 寫新郵件或回覆郵件的ac#vity• Services ‣ Run in the background, upda#ng your data sources and visible Ac#vi#es and triggering No#ﬁca#ons
Application Building Blocks(2/5)• Intents (An inter-application message- passing framework) ‣ Intent 綁定一次操作，它負責攜帶這次操作所 需要的資料以及操作的類型等• Content Providers (Sharable data stores) ‣ 在 Android 中，每個應用程式都是用自己的 user ID 及在自己的 process 中執行。這樣做的 好處是，可以保護系統及應用程式，避免被 其他不正常的應用程式所影響。
Application Building Blocks(4/5)• Broadcast Receivers (Listen for broadcast intents that match speciﬁc ﬁlter criteria) ‣ 當開發人員希望應用程式來對外部的事件做 一些處理時，可以使用Broadcast Intent Receiver。例如：當電話響時，或是網路資料 可以使用時，或是時間到了午夜時
Application Building Blocks(5/5)• Widgets ‣ Visual applica#on components that can be added to the home scree• Notiﬁcations ‣ No#ﬁca#ons let you signal users without stealing focus or interrup#ng their current Ac#vi#es
Application Life Cycle• Application 本身對自己的 life cycles 沒有 太多控制權，application components 聽 取 application states 的改變來做反應，尤 其隨時要對無預警的終止做準備• Each Android application runs in its own process, each of which is running a separate instance of Dalvik• 記憶體和行程完全由 run-time 管理
Application Priority and Process States(1/2)• An application’s priority is equal to its highest-priority component• If 2 applications have the same priority, the process that has been at a lower priority longest will be killed ﬁrst• Process priority is also affected by interprocess dependencies ‣ If an applica#on has a dependency on a Service or Content Provider supplied by a second applica#on, the secondary applica#on will have at least as high a priority as the applica#on it supports• All Android applications will remain running and in memory until the system needs resources for other applications
Application Priority and Process States(2/2) Externalizing Resources ! 59 • Active ProcessT he following list details each of the application states Critical Priorityshown in Figure 3-3, explaining in an “ac#ve” state ‣ components comprising it: is determinedby the application Ac#vi#es how the state 1. Active Process " Active‣ Broadcast Receivers processes processes A ctive (foreground) High Priority have application components interacting execu#ng onRe c e i v e with 2. Visible Process the user. T hese are the processes A ndroid is try- ing to keepevent handlers responsive by reclaiming resources. T here are generally very few of these processes, 3. Started Service Process ‣ Services only as a last resort. and they will be killed execu#ng onStart, A ctive processes include:or onDestroy onCreate, Low Priority A ctivities in andlers state; that is, event h an ‘‘active’’ 4. Background Process " those in the foreground responding to ‣ user events. YServices that have Running ou will explore A ctiv- 5. Empty Process itybeen in agged detailun in the states ﬂ greater to r later in this foreground chapter. FIGURE 3-3 . " Broadcast Receivers executing onRe c e i v e event handlers. " Services executing onS t a r t , onC r e a t e , or onDe s t r o y event handlers.
Externalize Resources(1/2)• Good practice to keep non-code resources like images and string constants external to your code• 9 primary resource types have different folders: simple values, Drawables, layouts, animations, styles, menus, searchables, XML, and raw resources
Externalize Resources(2/2)• These resources will be compiled as efﬁciently as possible and included in your application package• This process also generates an R class ﬁle that contains references to each of the resources you include in your project
Using Resources(1/2)• You access resources in code using the static R class• The R class contains static subclasses for each of the resource types for which you’ve deﬁned at least one resource• Each of the subclasses within R exposes its associated resources as variables (直接指向 resource table), with the variable names matching the resource identiﬁers ‣ R.string.app_name, R.drawable.icon
cess yourbe static. UseResources instance.s method on your application context, as s application’s the g e t Re s ou r c e Re s ou r caccess yourr application’sou r c e s ( ) ; to e s myRe s ou c e s = g e t Re s Resources instance.Re s ou r c e s class includes getters for each ofcthe available s ou r c e s types and generally wo Re s ou r c e s myRe s ou r e s = g e t Re resource ( ) ;ng in the resource I D you’d like an instance of. T he following code snippet shows an exa the helperhe Re s ou to e s class selection of resource values. of the available resource t T methods r c return a includes getters for each passing in the resource I D you’d like an instance of. T he following code Re s ou r c e s myRe s ou r c e s = g e t Re s ou r c e s ( ) ; using the helper methods to return a selection of resource values. Ch a r Se qu e n c e s t y l e dT e x t = myRe s ou r c e s . g e t T e x t ( R . s t r i ng . s t op_me s s a g e ) ; D r awa b l e i c onRe smyRec e s r myRegseou r awa b l=e (g e d Re s oul rec e pp_ i;c on ) ; = ou r s ou c e s . t D r c e s R . t r awa b . a s ( ) i n t op a qu eB l uCh = rmyRe s e n c c e ss. tgy lt e dTo rx(tR .= omyReopou r c _b l. u ee) t;T e x t ( R . s t r i ng e a Se qu ou r e e Co l e c l o r . s a qu e e s g D r awa b l e i c on = myRe s ou r c e s . g e t D r awa b l e ( R . d r awa b l e . a pp f l o a t bo r d e r W i d t h = myRe s ou r c e s . g e t D i me n s i on ( R . d i me n . s t a nd a r d_bo r d e r ) ; i n t op a qu eB l u e = myRe s ou r c e s . g e t Co l o r ( R . c o l o r . op a qu e _b An i ma t i on t r a nOu t ; t r a nOu t = An i ma t i onU t i l s . l o a dAn i ma t i on ( t h i s , R . a n i m . s p i n_ s h r i n k _ f a d e ) ; f l o a t bo r d e r W i d t h = myRe s ou r c e s . g e t D i me n s i on ( R . d i me n . s S t r i ng [ ] s t r i ngA r r a y ; s t r i ngA r r a y =An i mastouon e s .r g e t S t tr ;i ngA r r a y ( R . a r r a y . s t r i ng_ a r r a y ) ; myRe i r c t a nOu t r a nOu t = An i ma t i onU t i l s . l o a dAn i ma t i on ( t h i s , R . a n i m . s p i n t [ ] i n t A r r a y = myRe s ou r c e s . g e t I n t A r r a y ( R . a r r a y . i n t e g e r _ a r r a y ) ; S t r i ng [ ] s t r i ngA r r a y ;e-by-frame animatedt resourcesaare =inﬂatedsinto c e si ma e it onRe isngAc ersa. yY ou a r r areturnr thn s r i ngA r r y myRe ou r An t .g St r ou r r (R . can y . s t i g e t D r awa b l e and casting the return value, as shown here:
Referencing Resources within Resources(1/2)• You can also use resource references as attribute values in other XML resources• To reference one resource from another use @ notation ‣ attribute= "@[packagename:] resourcetype/ resourceidentifier"
Using System Resources• Use the native Android resource classes available from android.R, rather than the application-speciﬁc R class ‣ CharSequence hPpError = getString(android.R.string.hPpErrorBadUrl);• To access system resources in XML specify android as the package name
70 Referring to StylesAND Athe Current ! CHAPTER 3 CREATING APPLIC ATIO NS in CTIVITIES Theme • Referring to Styles in the Current Theme to ensure Using themes is an excellent way consistency for your application’s UI Using themes is an excellent way to ensure consistency for your applicatio deﬁne each style, A ndroid provides a shortcut to let you use styles from the • use ?android: rather than @ as a preﬁx to T o do this you use ? a nd r o i d : rather than @ as a preﬁx to the resource you the resource you want to use example shows a snippet of the preceding code but uses the current theme external resource. <Ed i t T e x t a nd r o i d : i d= " @+ i d / my Ed i t T e x t " a nd r o i d : l a y ou t _w i d t h= " f i l l _p a r e n t " a nd r o i d : l a y ou t _h e i gh t = " w r a p_ c on t e n t " a nd r o i d : t e x t = " @s t r i ng / s t op_me s s a g e " and r o i d : t e x t Co l o r = " ?and r o i d : t e x t Co l o r " /> T his technique lets you create styles that will change if the current theme ch
Creating Resources for Different Languages and Hardware(1/2)• Dynamic resource-selection mechanism• Using a parallel directory structure within the res folder. A hyphen (-) is used to separate qualiﬁers that specify the conditions you’re providing alternatives for
Creating Resources for Different Languages and Hardware(2/2)• list of qualiﬁers ‣ Mobile Country Code/Mobile Network Code ‣ Language and Region ‣ Screen Size ‣ Screen Width/Length ‣ Screen Orienta#on they must be used in the order ‣ Screen Pixel Density ‣ Touch Screen Type ‣ Keyboard Availability ‣ Keyboard Input Type ‣ UI Naviga#on Type
Runtime Conﬁguration Changes(1/3)• Android handles runtime changes to the language, location, and hardware by terminating and restarting each application and reloading the resource values• This default behavior isn’t always convenient or desirable• To have an Activity listen for runtime conﬁguration changes, add an android:conf igChanges attribute to its manifest node
Runtime Conﬁguration Changes(2/3)• Adding an android:conﬁgChanges attribute suppresses the restart for the speciﬁed conﬁguration changes, instead triggering the onConﬁgurationChanged method in the Activity• Conﬁguration changes you can specify ‣ Orienta#on, keyboardHidden, fontScale, locale, keyboard, touchscreen, naviga#on ‣ You can select mul#ple events you wish to handle yourself by separa#ng the values with a pipe (|).
Runtime Conﬁguration Changes(3/3) Handling configuration changes in code
Android Application Class(1/2)• Extending Application class enables you to ‣ Maintain applica#on states ‣ Transfer objects between applica#on components ‣ Manage and maintain resources used by several applica#on components
Android Application Class(2/2)• When your Application implementation is registered in the manifest, it will be instantiated when your application process is created
Application Life Cycle Events• onCreate ‣ Override this method to ini#alize your applica#on singleton and create and ini#alize any applica#on state variables or shared resources• onTerminate ‣ There is no guarantee of this method handler’s being called• onLowMemory• onConﬁgurationChanged ‣ Unlike with Ac#vi#es, your applica#on object is not killed and restarted for conﬁgura#on changes
Android Activities(1/3)• Each Activity represents a screen that an application can present to its users
Android Activities(2/3)• An empty Activity isn’t particularly useful, so the ﬁrst thing you’ll want to do is create the user interface with Views and layouts• To assign a user interface to an Activity, call setContent View from the onCreate method of your Activity
Android Activities(3/3)• In order to use an Activity in your application you need to register it in the manifest• For an Activity to be available from the main application launcher it must include an Intent Filter listening for the MAIN action and the LAUNCHER category
The Activity Life Cycle• Run time handles the termination and management of an Activity’s process• Activity States <=互相影響=> Application Priority
Activity Stacks(2/2)• The Activity state is determined by its position on the Activity stack• An application’s priority is inﬂuenced by its highest- priority Activity• When the Android memory manager is deciding which application to terminate to free resources, it uses this stack to determine the priority of applications based on their Activities.
Activity States• Active• Paused ‣ Be visible but will not have focus. This state is reached if a transparent or non-‐full-‐screen Ac#vity is ac#ve in front of it• Stopped ‣ When an Ac#vity isn’t visible, it ‘‘stops.’’ It is now a candidate for termina#on when the system requires memory elsewhere• Inactive ‣ Ader an Ac#vity has been killed, and before it’s been launched, it’s inac#ve
Monitoring State Changes• Android provides a series of event handlers that are ﬁred when an Activity transitions through its full, visible, and active lifetimes