Programming Mobile Applications for Android Handheld systems, Part 1
Course page: https://class.coursera.org/androidpart1-001/wiki/Module_1%3A_Android_Development_Environment
By Dr. Adam Porter
Source code available at: https://github.com/aporter/coursera-android
Week 1 - Android Platform and Development Environment
Introduction to the Android Platform
- We use Android SDK for development.
- See http://developer.android.com/training for documentation.
- 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:
- Core java libraries
- Dalvik virtual machine: executes the apps. See video: Dalvik VM Internals by Dan Bornstein
- 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
Android Development Environment
- See http://developer.android.com/sdk for info on supported OS.
Ensure we have JDK6 installed (not JDK7 as it is not fully supported by android). See: http://www.oracle.com/technetwork/java/javase/downloads
- 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 #or 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"
- We can have interactions between 2 emulators (calling its port number for instance)
- More on emulators at: http://developer.android.com/guide/developing/devices/emulator.html
- DDMS tools contains: file explorer, logcat, traceview, ui hirarchyview.
- building blocks for UI elements: http://developer.android.com/design/building-blocks
Week 2 - Application Fundamentals and the Activity Class
Application Fundamentals
- 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:
- define resources and source code
- build an android package (.apk)
- Signing of the .apk
- Installation and run of the apk
- For details on building stages see: http://developer.android.com/guide/developing/building
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
- More info on manifest files at: http://developer.android.com/guide/topics/manifest/manifest-intro.html
Install and run
- We can use the adb tool directly to install a package.
- But the package needs to be manually signed first: http://developer.android.com/tools/publishing/app-signing.html
The Activity Class
- 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:
- call super.onCreate()
- set activity content view
- retain refs on UI elements
- 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:
- Specify the activity to start in an intent.
- 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.
Week 3 - Intents, Permissions, and the Fragments Class
The Intent Class
- Intent class is a data structure, can be used to represent:
- An operation to be performed.
- 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_DIAL,
ACTION_EDIT,
ACTION_SYNC,
ACTION_MAIN, etc…
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:
Uri.parse("tel:+155555555");
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" /> </intent-filter> </activity>
- 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
Permissions
- 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:
<permission android:name="course.example.permission.BOOM_PERM" android:description="@string/boom_perm_string" android:label="@string/boom_permission_label_string"> </permission>
- THen this permission is added as part of the application tag:
<application ... android:permission="course.example.permission.BOOM_PERM" ...> </application>
- 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.
The Fragment Class
- 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:
- get ref to FragmentManager
- begin a FragmentTransaction
- add fragment to activity
- 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.
Week 4 - User Interface Classes
User Interface Classes
- 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