SlideShare a Scribd company logo
Ch3. Creating
Application & Activities
           Browny
         06, May, 2011
Outline

• Application Building Blocks
• Application Manifest
• Application Priority and Process States
• Externalize Resources
• Android Application Class
• Android Activities
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#fica#ons
Application Building Blocks(2/5)

• Intents (An inter-application message-
  passing framework)
  ‣ Intent	
  
                                                    ...

• Content Providers (Sharable data stores)
  ‣       	
  Android	
                                    	
  user	
  
      ID	
                  	
  process	
  

                                        	
  (con#nue...)
Application Building Blocks(3/5)

• Content Providers (Sharable data
  stores)
  ‣         Contacts	
  
                           	
  Email	
  
                                           	
  Contacts	
  


  ‣
       Android	
                  	
  Content	
  Provider	
  
Application Building Blocks(4/5)


• Broadcast Receivers (Listen for
  broadcast intents that match specific
  filter criteria)
  ‣
                      	
  Broadcast	
  Intent	
  
      Receiver
Application Building Blocks(5/5)


• Widgets
  ‣ Visual	
  applica#on	
  components	
  that	
  can	
  be	
  
      added	
  to	
  the	
  home	
  scree

• Notifications
  ‣ No#fica#ons	
  let	
  you	
  signal	
  users	
  without	
  
      stealing	
  focus	
  or	
  interrup#ng	
  their	
  current	
  
      Ac#vi#es
Application Manifest
•     Android
                    (Activity, Service, )
                      AndroidManifest.xml


•   AndroidManifest.xml
                  .apk


•                         Manifest   intent filter
      permissions
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 first
•   Process priority is also affected by
    interprocess dependencies
•   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 Process
T he following list details each of the application states                                                Critical Priority
shown in Figure 3-3, explaining how the state is determined
              ‣ components comprising it: state
by the application
                    Ac#vi#es	
  in	
  an	
  “ac#ve”	
                             1. Active Process


   "    Active‣ Broadcast	
  Receivers	
   processes
               processes A ctive (foreground)
                                                                                                          High Priority
        have application components interacting with
                    execu#ng	
  onReceive	
  event	
                              2. Visible Process
        the user. T hese are the processes A ndroid is try-
        ing to keephandlers by reclaiming resources.
                     responsive
        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 fl greater to	
  r later in this
                    chapter.
                       foreground                                         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
  efficiently as possible and included in your
  application package


• This process also generates an R class file
  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 defined
    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 identifiers
    ‣   R.string.app_name,	
  R.drawable.icon
Using Resources(2/2)


•
    getResources   resource table
            Resource


• Resource
                  getters   (
    resource ID                 getter   )
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 =inflatedsinto 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"
Referencing Resources within
       Resources(2/2)
Using System Resources

• Use the native Android resource classes
  available from android.R, rather than the
  application-specific R class
 ‣   CharSequence httpError = getString(android.R.string.httpErrorBadUrl);



• 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
      define each style, A ndroid provides a shortcut to let you use styles from the
       • use ?android: rather than @ as a prefix to
      T o do this you use ? a nd r o i d : rather than @ as a prefix 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 qualifiers that specify the
  conditions you’re providing alternatives for
Creating Resources for Different
     Languages and Hardware(2/2)
•    List of qualifiers
    ‣   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 Configuration 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
  configuration changes, add an
  android:configChanges attribute to its
  manifest node
Runtime Configuration Changes(2/3)

• Adding an android:configChanges attribute
   suppresses the restart for the specified
   configuration changes, instead triggering the
   onConfigurationChanged method in the
   Activity
• Configuration 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 Configuration 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
Skeleton Application Class
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
•    onConfigurationChanged
    ‣ Unlike	
  with	
  Ac#vi#es,	
  your	
  applica#on	
  object	
  is	
  not	
  killed	
  
         and	
  restarted	
  for	
  configura#on	
  changes
Android Activities(1/3)

• Each Activity represents a screen that an
  application can present to its users
Android Activities(2/3)

• The first 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(1/2)
Activity Stacks(2/2)

• The Activity state is determined by its
  position on the Activity stack
• An application’s priority is influenced 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
    ‣ Aaer	
  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 fired when an Activity transitions
  through its full, visible, and active lifetimes
Ch3 creating application and activities
Thank you :)

More Related Content

Viewers also liked (8)

PPT
11 15
99qwert
 
PPS
Spanishisdifferent
yak072
 
PPS
5cosasimportantes
yak072
 
PPS
Cartadelpene
yak072
 
PPS
Amistad
yak072
 
PDF
Ch4 creating user interfaces
Shih-Hsiang Lin
 
PPTX
Project Hosting by Google
Shih-Hsiang Lin
 
PPTX
Git basic
Shih-Hsiang Lin
 
11 15
99qwert
 
Spanishisdifferent
yak072
 
5cosasimportantes
yak072
 
Cartadelpene
yak072
 
Amistad
yak072
 
Ch4 creating user interfaces
Shih-Hsiang Lin
 
Project Hosting by Google
Shih-Hsiang Lin
 
Git basic
Shih-Hsiang Lin
 

Similar to Ch3 creating application and activities (20)

PDF
Android Jump Start
ConFoo
 
PPTX
Mobile Application Guideline | Mobile App Development Company
Arna Softech Private Limited
 
PDF
Android Development
mclougm4
 
PDF
Android Bootcamp
ahkjsdcsadc
 
PPTX
Android Application Development
Azfar Siddiqui
 
PDF
Android Development...The 20,000-Foot View
CommonsWare
 
PDF
Mobile Application Development Lecture 05 & 06.pdf
AbdullahMunir32
 
PPT
Mc android
Moresh Kashikar
 
PPTX
Basics 4
Michael Shrove
 
PDF
Day1 before getting_started
Ahsanul Karim
 
PDF
Android development - the basics, MFF UK, 2012
Tomáš Kypta
 
PPT
Android overview
Ashish Agrawal
 
PPTX
App Fundamentals and Activity life cycle.pptx
ridzah12
 
PDF
Android Application Components
JAINAM KAPADIYA
 
PDF
Lecture3
jousterlabs
 
PPTX
Android apps development
Raman Pandey
 
PDF
Android application development
Linh Vi Tường
 
PPT
Synapseindia android apps overview
Synapseindiappsdevelopment
 
PDF
Android Components & Manifest
ma-polimi
 
PPTX
Android application fundamentals
John Smith
 
Android Jump Start
ConFoo
 
Mobile Application Guideline | Mobile App Development Company
Arna Softech Private Limited
 
Android Development
mclougm4
 
Android Bootcamp
ahkjsdcsadc
 
Android Application Development
Azfar Siddiqui
 
Android Development...The 20,000-Foot View
CommonsWare
 
Mobile Application Development Lecture 05 & 06.pdf
AbdullahMunir32
 
Mc android
Moresh Kashikar
 
Basics 4
Michael Shrove
 
Day1 before getting_started
Ahsanul Karim
 
Android development - the basics, MFF UK, 2012
Tomáš Kypta
 
Android overview
Ashish Agrawal
 
App Fundamentals and Activity life cycle.pptx
ridzah12
 
Android Application Components
JAINAM KAPADIYA
 
Lecture3
jousterlabs
 
Android apps development
Raman Pandey
 
Android application development
Linh Vi Tường
 
Synapseindia android apps overview
Synapseindiappsdevelopment
 
Android Components & Manifest
ma-polimi
 
Android application fundamentals
John Smith
 
Ad

More from Shih-Hsiang Lin (10)

PDF
Introduction to Apache Ant
Shih-Hsiang Lin
 
PDF
Introduction to GNU Make Programming Language
Shih-Hsiang Lin
 
KEY
Ch6 file, saving states, and preferences
Shih-Hsiang Lin
 
PDF
[C++ gui programming with qt4] chap9
Shih-Hsiang Lin
 
PDF
Ch5 intent broadcast receivers adapters and internet
Shih-Hsiang Lin
 
PDF
[C++ GUI Programming with Qt4] chap7
Shih-Hsiang Lin
 
PPTX
[C++ GUI Programming with Qt4] chap4
Shih-Hsiang Lin
 
PPTX
Function pointer
Shih-Hsiang Lin
 
PPT
Introduction to homography
Shih-Hsiang Lin
 
PDF
An Introduction to Hidden Markov Model
Shih-Hsiang Lin
 
Introduction to Apache Ant
Shih-Hsiang Lin
 
Introduction to GNU Make Programming Language
Shih-Hsiang Lin
 
Ch6 file, saving states, and preferences
Shih-Hsiang Lin
 
[C++ gui programming with qt4] chap9
Shih-Hsiang Lin
 
Ch5 intent broadcast receivers adapters and internet
Shih-Hsiang Lin
 
[C++ GUI Programming with Qt4] chap7
Shih-Hsiang Lin
 
[C++ GUI Programming with Qt4] chap4
Shih-Hsiang Lin
 
Function pointer
Shih-Hsiang Lin
 
Introduction to homography
Shih-Hsiang Lin
 
An Introduction to Hidden Markov Model
Shih-Hsiang Lin
 
Ad

Recently uploaded (20)

PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
Controller Request and Response in Odoo18
Celine George
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
Horarios de distribución de agua en julio
pegazohn1978
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Introduction presentation of the patentbutler tool
MIPLM
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 

Ch3 creating application and activities

  • 1. Ch3. Creating Application & Activities Browny 06, May, 2011
  • 2. Outline • Application Building Blocks • Application Manifest • Application Priority and Process States • Externalize Resources • Android Application Class • Android Activities
  • 3. 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#fica#ons
  • 4. Application Building Blocks(2/5) • Intents (An inter-application message- passing framework) ‣ Intent   ... • Content Providers (Sharable data stores) ‣  Android    user   ID    process    (con#nue...)
  • 5. Application Building Blocks(3/5) • Content Providers (Sharable data stores) ‣ Contacts    Email    Contacts   ‣ Android    Content  Provider  
  • 6. Application Building Blocks(4/5) • Broadcast Receivers (Listen for broadcast intents that match specific filter criteria) ‣  Broadcast  Intent   Receiver
  • 7. Application Building Blocks(5/5) • Widgets ‣ Visual  applica#on  components  that  can  be   added  to  the  home  scree • Notifications ‣ No#fica#ons  let  you  signal  users  without   stealing  focus  or  interrup#ng  their  current   Ac#vi#es
  • 8. Application Manifest • Android (Activity, Service, ) AndroidManifest.xml • AndroidManifest.xml .apk • Manifest intent filter permissions
  • 9. 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
  • 10. 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 first • Process priority is also affected by interprocess dependencies • All Android applications will remain running and in memory until the system needs resources for other applications
  • 11. Application Priority and Process States(2/2) Externalizing Resources ! 59 • Active Process T he following list details each of the application states Critical Priority shown in Figure 3-3, explaining how the state is determined ‣ components comprising it: state by the application Ac#vi#es  in  an  “ac#ve”   1. Active Process " Active‣ Broadcast  Receivers   processes processes A ctive (foreground) High Priority have application components interacting with execu#ng  onReceive  event   2. Visible Process the user. T hese are the processes A ndroid is try- ing to keephandlers by reclaiming resources. responsive 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 fl greater to  r later in this chapter. foreground 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.
  • 12. 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
  • 13. Externalize Resources(2/2) • These resources will be compiled as efficiently as possible and included in your application package • This process also generates an R class file that contains references to each of the resources you include in your project
  • 14. 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 defined 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 identifiers ‣ R.string.app_name,  R.drawable.icon
  • 15. Using Resources(2/2) • getResources resource table Resource • Resource getters ( resource ID getter )
  • 16. 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 =inflatedsinto 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:
  • 17. 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"
  • 19. Using System Resources • Use the native Android resource classes available from android.R, rather than the application-specific R class ‣ CharSequence httpError = getString(android.R.string.httpErrorBadUrl); • To access system resources in XML specify android as the package name
  • 20. 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 define each style, A ndroid provides a shortcut to let you use styles from the • use ?android: rather than @ as a prefix to T o do this you use ? a nd r o i d : rather than @ as a prefix 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
  • 21. 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 qualifiers that specify the conditions you’re providing alternatives for
  • 22. Creating Resources for Different Languages and Hardware(2/2) • List of qualifiers ‣ 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
  • 23. Runtime Configuration 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 configuration changes, add an android:configChanges attribute to its manifest node
  • 24. Runtime Configuration Changes(2/3) • Adding an android:configChanges attribute suppresses the restart for the specified configuration changes, instead triggering the onConfigurationChanged method in the Activity • Configuration 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  (|).
  • 25. Runtime Configuration Changes(3/3) Handling configuration changes in code
  • 26. 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
  • 27. Android Application Class(2/2) • When your Application implementation is registered in the manifest, it will be instantiated when your application process is created
  • 29. 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 • onConfigurationChanged ‣ Unlike  with  Ac#vi#es,  your  applica#on  object  is  not  killed   and  restarted  for  configura#on  changes
  • 30. Android Activities(1/3) • Each Activity represents a screen that an application can present to its users
  • 31. Android Activities(2/3) • The first 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
  • 32. 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
  • 33. The Activity Life Cycle • Run time handles the termination and management of an Activity’s process • Activity States <= => Application Priority
  • 35. Activity Stacks(2/2) • The Activity state is determined by its position on the Activity stack • An application’s priority is influenced 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.
  • 36. 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 ‣ Aaer  an  Ac#vity  has  been  killed,  and  before  it’s  been   launched,  it’s  inac#ve
  • 37. Monitoring State Changes • Android provides a series of event handlers that are fired when an Activity transitions through its full, visible, and active lifetimes