Programming Mobile Applications for Android Handheld systems, Part 1

  • Lowest layer: Linux Kernel layer
    • Provides permission
    • manage memory
    • handle files and network IO
    • device drivers
    • android specific:
      • Power management service
      • memory sharing
      • low memory killer
      • interprocess communication
  • Native libraries layer:
    • System C library (bionic libc)
    • Surface manager
    • Media framework
    • webkit
    • OpenGL
    • SQLite
    • Android runtime:
  • Application framework layer:
    • Package manager: manager list of installed apps.
    • Window manager: handles all windows (main window, sub windows).
    • View system (buttons, icons, …)
    • Resource manager: handle non compiled resources (strings, graphics, etc…)
    • Activity Manager: supports mutiples activities in an app.
    • ContentProvider: inter app data sharing.
    • LocationManager: location and movement indications.
    • NotificationManager: send notifications.
  • Application layer:
    • Home screen, phone dialer, web browser
  • Emulated Android are called Virtual Devices.
  • Emulators are pretty slow
  • Emulators have some features unavailable
  • With Emulator running we could do:
    telnet locahhost 5554 # port is an example.
    # then:
    network speed egde
    network speed full
    power capacity 5
    power status not-charging
    geo fix 0.00 40.00
    # Emulate incomming sms:
    sms send 301555555 "This is a text message"
  • 4 building blocks (java classes)
    • Activity
    • Service
    • BroadcastReceiver
    • ContentProvider
  • Activity class:
    • Present the UI interface
  • Service class:
    • Run in the background
    • perform long operation
    • provide way for processes to request operation and share data
  • BroadcastReceiver:
    • Listens and responds to events (= intents)
  • Content Provider:
    • Store and share data.
  • Application building steps:
    1. define resources and source code
    2. build an android package (.apk)
    3. Signing of the .apk
    4. Installation and run of the apk

Defining resources

  • 3 types of string resources: strings/string arrays/plurals
  • To access strings:
    • From another resource: @string/string_name
    • in java code: R.string.string_name
  • To specify the language when defining strings we use the language code in the folder name:
    • res/values/strings.xml → res/values-fr/strings.xml
  • Layouts are stored in res/layouts/*.xml
  • layouts may depend on device config:
    • res/layout-land/* : when we are in landscape mode
  • android will define the R class for a project

Implementing classes

  • Write at least one activity.
  • onCreate:
    • restore saved state
    • set content view
    • initialze UI elements
    • attach code to UI elements

Package application

  • Information written in AndroidManifest.xml, including:
    • Name of app
    • list of components
    • permissions
    • hardware features
    • minimum API level

Install and run

  • Activities should be modular.
  • Task: set of related activities (can be in multiple apps!)
  • Task backstack : navigtion between activities
  • Activities are pushed/poped from the task backstack.
  • pressing “back” will normallly kill the current activity on the stack.
  • Activity lifecycle
  • depends on user behavior (pression back ?)
  • can be killed be android directly.
  • Activity can be in Resumed/Running state.
  • Can also be paused, can be terminated
  • Can be stopped
  • Android will annonce lifecycle changes:
    • onCreate()
    • onStart()
    • onResume()
    • onPause()
    • onStop()
  • Typical order: onCreate() → onStart() → onResume() → activity running.
  • Then activity can be stopped with: onPause() → onStop() → onDestroy() → activity shutdown.
  • onStart() : called when activity is about to become visible.
  • onStop() : called when activity is about to become invisible.
  • onResume() : activity is about to become available for user interaction.
  • onPause() : activity will not be availabel for user interaction anymore.
  • onStop() can be skipped if android kills the activity.
  • API and patterns to control activities.
    • onCreate(): used to initialize:
      1. call super.onCreate()
      2. set activity content view
      3. retain refs on UI elements
      4. configure the UI elements.
    • onRestart(): called when an activity was stopped and is about to start again.
    • onStart(): typically to handle when visible-only behaviors or loading persistent application state.
    • onResume(): start foreground only behavior.
    • onPause(): kill foreground animations, save persistent states the user updated.
    • onStop(): caching activity states. Note that onStop() may nt be called if android kills the activity.
    • onDestroy(): to release activity resources. (may not be called either)
  • Start an activity programmatically:
    1. Specify the activity to start in an intent.
    2. Pass the intent to methods such as:
      • startActivity()
      • startActivityForResult() : expect a result to be sent back to our activity.
    • activity.setResult(code, data) → called to assign a result to an activity.
      • code could be RESULT_CANCELED, RESULT_OK, etc…
    • activity.onActivityResult(requestCode, resultCode, data)
  • Configuration changes:
    • keyboard, orientation, locale, etc…
    • When changed at run time android kills the activity then restart it with the proper resources.
  • To speed up the process, we may:
    • cache an arbitrary object with the state information → onRetainNonConfigurationInstance()
    • object can then be retrieved with getLastNonConfigurationInstance() (those methods are deprecated (should use fragment class instead))
  • manually handle the configuration change.
    • Should be defined in the androidManifest.xml file.
    • Activity will then receive onConfigurationChanged(), will receive a configuration object with the appropriate details.
  • Intent class is a data structure, can be used to represent:
    1. An operation to be performed.
    2. An event that has occured.
  • Intents provide a flexible language to specify operations to be performed.

Intent fields

  • Action: (string) naming the action to be performed, like:

Action can be set on construction or with the setAction method.

  • Data: data associated with the Intent, formated as an URI.

URI can be parsed with for instance:


Data can be set on construction or with the setData method.

  • Category: additional info about the kind of component that should handle the intent.
  • Type: Specify the MIME tye of the data. (ex: image/*, image/png, image/jpeg, text/html, text/plain). If not specified, will be infered by Android.
  • Component: Component that should receive this intent.
  • Extras: map of key-value pairs
  • Flags: how the intent should be handled. For instance Intent.FLAG_DEBUG_LOG_RESOLUTION to get more info on the activity selected when using the intent.

Explicit Activation

  • Intent can be constructed from context and class:
    new Intent(LoginScreen.this, HelloAndroid.class);

Implicit Activation

  • Android will perform intent resolution : matching the intent with the properties/capabilities of the Activities installed on the device.
  • Activities specify IntentFilters which describe which operation an activity can handle (placed in AndroidManifest.xml or generated programmatically)
  • For resolution, Android uses the fields: Action, Data, Type and Category

Specifying IntentFilters

  • In manifest.xml file:
    <activity ...>
      <intent-filter ...>
        <action android:name="actionName" />
  • Activity can provide a priority to decide if it should be given the priority when multiples activities match the intent. Priority should be between -1000 and 1000.
  • We can use the following command to retrieve info on the available intent filters:
    adb shell dumpsys package
  • Permission architecture
    • Permissions represented as string
    • Stored in AndroidManifest.xml file:
      • Declaring permissions the app uses itself:
        <uses-permission> tag
      • Declaring permissions the app requires of other components that want to us e it.
  • Define and using app level permissions.
    • New permission defined with <permission> tag:
    • THen this permission is added as part of the application tag:
  • Component specific permissions and permissions API
    • Component permissions take precedence on application level permissions.
    • Activity permissions: restricts which components can start the associated activity.
    • Service permissions: restricts which component can start and bind to a service.
    • BroadcastReceiver permissions: restricts which component can send and receive broadcasts
    • ContentProvider permissions: restricts read and write the data in a contentprovider.
  • Android throws SecurityException on permission failure.
  • Fragments represents portions of UI within an activity.
  • Fragments are hosted by activities (0 or more fragments).
  • One fragment can be used by 0 or more activities.
  • Fragment lifecycle is coordinated with the lifecycle of its containing activity.
  • Fragment can be in running/resumed state: visible
  • Can be paused: activity is visible but without focus.
  • Can be stopped: invisible.

Lifecycle callback methods

  • onAttach() → onCreate() → onCreateView() → onActivityCreated()
  • activity onStart() → fragment onStart()
  • activity onResume() → fragment onResume()
  • activity onPause() → fragment onPause()
  • activity onStop() → fragment onStop()
  • onDestroyView() : release the view objects.
  • onDestroy() : release fragment resources.
  • onDetach()
  • Fragments can be statically added to activity (adding them in layout file)
  • Fragments can be added programmatically using the FragmentManager:
    1. get ref to FragmentManager
    2. begin a FragmentTransaction
    3. add fragment to activity
    4. commit the FragmentTransaction.
  • Dynamic addition of fragments:
    • transaction.addTOBackStack(null) : to allow stack tracking when using the back button.
    • fragManager.executePendingTransactions(): to execute the pending transactions immediately.

Configuration changes

  • setRetainInstance(true) : kill the activity but keep the fragment. Whan the new activity is create, the fragments onDestroy() and onCreate() methods will NOT be called.
  • View class
    • Occupy rect space,
    • Draw themself and handle events directed to them.
    • Predefined views:
      • Button
        • User can click on it.
      • ToggleButton
        • Stays pressed (2-state button)
        • Light indicator
      • Checkbox
        • Also a kind of 2-state button.
      • RatingBar:
        • Row of stars
      • AutoCompleteTextView:
        • Displays text
        • Editable
        • Will provide an auto complete list during typing.
  • View operations:
    • Set visibility
    • Change the check state
    • Set listener
    • Set orientation, opacity, background
    • Set the focus.
  • View events and operations
    • User interaction:
      • Touch
      • OnClickListener.onClick()
      • OnLongClickListener.onLongCLick()
      • OnFocusChangeListener.onFocusChange()
      • OnKeyListener.onKey()
    • System control
      • lifecycle control
      • onMeasure() → provide our own measure
      • onLayout()
      • onDraw() → draw the view
      • onFocusChange()
      • onKeyUp()/onKeuDown()
  • View groups:
    • View are organized in a tree
    • ViewGroups are invisible views
    • RadioGroup
      • Contains exclusive radio buttons
    • TimePicker
    • DatePicker
    • WebView : display a webpage
    • MapView : display maps and allow interaction
  • Adapter and AdapterViews
    • Child views are managed by the adapter.
    • ListView:
      • scrollable list of selectable items
      • adapter: ListAdapter
    • Spinner:
      • Scrollable list in dropdown list.
      • managed by SpinnerAdapter
    • Gallery:
      • Horizontally scrolling list
  • Layouts:
    • LinearLayout: arrange children horizontally or vertically.
    • RelativeLayout: positioning relative to parents and sibling.
    • TableLayout : rows and colunms
    • GridView: 2D scrollable grid.
  • Menus & ActionBar
    • Activities can add items to a menu
    • Activities can respond when a menu items is clicked.
    • We have:
      • Options menu: menu of the “menu button”
      • Context menu: shown when a view is pressed and hold
      • Submenu: activited from menu item.
    • Creating menu:
      • define content in res/menu/filename.xml
      • onCreateOptionsMenu()
      • onCreateContextMenu()
      • ⇒ use menu inflater
      • onXXXItemsSelected() gets called
    • Advanced features:
      • Grouping items
      • shortcut keys
      • Intents to menu items
    • ActionBar similar desktop menu bar.
    • Fragments should call setHasOptionsMenu(true) to add menu items.
    • ActionBar.Tab used to display multiple “tabs”
  • Dialogs
    • AlertDialog
    • ProgressDialog
    • DatePickerDialog
  • public/courses/android/android_programming_part1/android_programming.txt
  • Last modified: 2020/07/10 12:11
  • (external edit)