Android SDK Training Notes with Eclipse
- Eclipse
- Android is an operating system based on Linux
- designed to be run on mobile devices
- Android Platform contains application framework for creation of apps
- Android Architectures – Software Stack
- base is Linux Kernel – highly optimized for mobile operating systems
- android runtime and set of libraries then enable behavior of operating system
- application framework sits on runtime
- applications are top of software stack
- application framework sits on runtime
- android runtime and set of libraries then enable behavior of operating system
- Linux Kernel has a set of drivers to interface with onboard devices
- Android Runtime contains core libraries and Dalvik virtual machine (jvm) replaces conventional java compiler and is super optimized
- Libraries contain libraries to address features of android
- Application Framework has modules to control different components of applications
- including activity managers, location managers, window managers
- Applications are programs
- at least home screen, browser, contacts, and phone
- more and more new apps are included with operating system
- can add as many apps as memory allows to application layer in stack
- App Architecture
- apps are made up of components
- Activities represent the user interface, the screen itself (represented by java class)
- Widgets manage display and user interactivity
- Services perform background jobs (invisible to user)
- Broadcast receivers react to system messages, from operating system or other apps
- apps are made up of components
- Component Architecture
- Each component is implemented as Java class
- have access to both java classes included in sdk and custom java classes
- ex. an activity is instance of android.app.Activity
- button is instance of android.widget.Button
- Each component is implemented as Java class
- Java – compiler uses Android-specific Java implementation
- primarily Java 5 APIs, with a small amount of Java 6
- base is Linux Kernel – highly optimized for mobile operating systems
- First version released in 9/08
- had a browser, camera support, search, maps, etc.
- Creating a Virtual Device
- From inside Eclipse, select Windows > Android Virtual Device Manager
- can select from large number of possible devices (top tab), a popular one for testing is Nexus 7
- select Nexus 7 and hit create AVD
- fill in parameters, popular target is Android 4.3 JellyBean
- set Memory Options to 768
- set SD Card slot to 64MB just in case you want to do card programming for application
- click OK to create AVD
- Now select device and click “Start”
- select Nexus 7 and hit create AVD
- AMR CPU devices can be slow to run, use Intel Devices for increased responsiveness
- to get Intel devices, must install more from SDK Manager
- must get Intel System Images for different packages
- must get Intel Processor from Extra’s at bottom of page
- If using newer OS, must get haxm from software.intel.com
- now install haxm by closing everything and find software in sdk > extras > intel > select executable entitled “intelhaxm-android”
- doesn’t work on all computers, including mine
- if it does work, follow same process but use different CPU and check “Use Host GPU” at bottom
- doesn’t work on all computers, including mine
- to get Intel devices, must install more from SDK Manager
- can select from large number of possible devices (top tab), a popular one for testing is Nexus 7
- From inside Eclipse, select Windows > Android Virtual Device Manager
- USB Driver
- if wanting to test on actual android device, must load Google USB Drivers for Windows
- visit developer.android.com/sdk/win-usb.html
- USB drivers vary for different phones, best to contact manufacturers customer service or download drivers from website
- if wanting to test on actual android device, must load Google USB Drivers for Windows
- Setting Device
- Once phone is connected and there are no flags in device manager, open eclipse > Window > Other > Device to open a panel at the bottom of eclipse with your device listed
- New Project
- Once devices are created, go to File > New Project to create a new project and set parameters
- Android Application > Take most defaults and follow directions on how to define parameters
- Once created, go to Run > Run to run your project on the device of your choice
- Once devices are created, go to File > New Project to create a new project and set parameters
- Directory Structure
- First Folder in Project Explorer panel is src folder contains Java code
- one package contains classes which represent apps activities
- this package is registered in manifest ID
- gen folder is all classes automatically generated
- one important is R class
- SDK folder points to jar file which is a part of SDK install
- notice API versions
- can change API versions by changing target SDK
- Project > Project Properties > Android and choose Android Version then Project > Clean and wait a few moments, will change Android version
- Android Private Library contains android support library, to emulate modern features on older devices
- automatically installed in newer version of Eclipse
- Assets folder contains anything that doesn’t need to be directly addressable as java objects
- not like RES folder, which contains java objects
- bin directory is managed for you, includes compiled class files and other critical resources, don’t touch this directly
- if see something suspicious, clean project and see if it is removed
- libs directory is great place to add java libraries
- comes with support library
- also good for 3rd party libraries, but not added to projects class file automatically, must do that ourselves
- res contains files that define appearance and behavior
- graphics go in drawable folders
- layout, menu, and values contains xml files that declare behaviors
- anim is animation resource
- color is predefined colors
- AndroidManifest.xml creates graphical UI that allows changes to be made to app behavior
- one package contains classes which represent apps activities
- First Folder in Project Explorer panel is src folder contains Java code
- Android is an operating system based on Linux
- Manifest – AndroidManifest.xml is xml file the describes capabilities of app to device
- open into a graphical UI
- choose final tab on bottom of view to open file in XML
- manifest creates a XML prefix in line 2
- package name must be unique and correspond with file in src folder
- versionCode is integer that must be increased each time app is updated on app store
- versionName can handle other info
- uses-sdk
- can set maxSdkVersion if want to compile on one version but allow for use on other
- application
- points to resources and properties
- icon points to icon creative
- label describes how app will be represented in start screen and application list
- to jump to resource, hold CTRL + click on resource to open XML file in which resource is defined
- theme points to applications theme and styling
- Activity Elements
- each screen in application is activity
- each activity must be registered with application manifest file
- name is fully qualified name of activity, and must match name of com package
- can also use “.” for placeholder for current package
- label points to app name
- intent-filter tells OS when user starts up app, this activity should start first.
- points to resources and properties
- choose final tab on bottom of view to open file in XML
- API Docs
- go to developers.android.com
- click on develope
- choose between training, API guides, and reference
- click on develope
- documentation is also available thru Eclipse
- highlight property in question and click help > dynamic help
- go to developers.android.com
- Layouts
- to edit layouts, must find MainActivity.xml
- edit onCreate
- to create new layout, go to res folder on left, expand and select layouts, then right-click and select New > Android XML File
- can chose variety of types, give new file a name (lowercase, no spec chars)
- then indicate root element
- in default layout, relative is used
- to edit layouts, must find MainActivity.xml
- Views and Groups
- XML layout files describe appearance of android screen
- visual widgets are java views or instances of view class
- view class is android.view.View
- textview is android.widget.TextView
- button is android.widget.button
- compound button is android.widget.CompoundButton
- button is android.widget.button
- view group is android.widget.ViewGroup
- ViewGroups are layout containers
- linearLayout lays child objects horiz. and vertically
- RelativeLayout lays out child objects relative to self or other child objects
- GridView creates 2D Scrollable grid
- ListView creates a vertical list of scrollable items
- AbsoluteLayout, DrawerLayout, ViewPager, and many others
- Mostly want to use linear and relative layouts
- ViewGroups are layout containers
- textview is android.widget.TextView
- view class is android.view.View
- visual widgets are java views or instances of view class
- XML layout files describe appearance of android screen
- Dimensions
- dimensions are units of measurement to control placement and size of visual objects
- used for placements and size of all visual components
- these are set in XML layout files or programmatically
- they can also be set at java runtime
- Device-Independent Pixels (dp) – Important
- devices greatly vary, so dp is used to set position and size of containers and allow the device to change the layout but still retain original design
- alters pixels by ratios
- devices greatly vary, so dp is used to set position and size of containers and allow the device to change the layout but still retain original design
- Scale-Independent Pixels (sp)
- use dp for placement of objects, use sp for font size
- Can also use fixed width measurements, but don’t do this
- Dimension Resources
- dimension resource files define reusable dimensions
- place dimension resource file in res/values folder
- default is dimens.xml
- root element is resources, and child elements are dimen elements
- can set name to any resource id you want
- all lower case and use underscore
- to use dimension resource
- android.parameter=”@dimen/string_name”
- ex. android:paddingBottom=”@dimen/activity_vertical_margin”
- where: <dimen name=”activity_vertical_margin”>16dp</dimen> is contained in dimens XML file
- android.parameter=”@dimen/string_name”
- Managing Multiple Screens can be complex
- create default dimensions XML file in res/values
- then set alternative settings for different sizes and orientations
- in project explorer
- values folder has default dimensions
- values-sw600dp folder holds dimens for screen where, if held on long rectangle, the short size has value >= 600dp
- same for 720dp, -land is if screen is held in landscape orientation
- can set dimensions in code
- each view or widget has layoutParams object
- can set height, width, etc. as properties of layoutParams
- dimensions are units of measurement to control placement and size of visual objects
- Linear Layout
- adds content in linear fashion, one element after another
- in XML view, can see that objects are added with separate id instances
- android:id=”@+id/button1”
- @+id is add a unique identifier
- within layout file, each object should have it’s own id
- android:id=”@+id/button1”
- open into a graphical UI
- Debugging
- if android debug bridge (adb) is used to run apps on emulators and devices
- gets messages and can even receive custom message
- always approve logcat view
- logcat view shows series of messages
- tag indicates source of message
- android runtime and dalvik are system level
- activity level is application level
- tag indicates source of message
- because mistakes can be made when debugging and naming strings, refactoring can be used to minimize the opportunity for typographical errors
- select entire string and right click > refactor > extract constant
- call it whatever you want, all caps
- select entire string and right click > refactor > extract constant
- comment out log calls when ready for deployment as they are not automatically removed
- toast messages are simple visual messages that appears momentarily on screen
- managed by the application framework, but triggered by developer
- Breakpoints allow one to watch the values of variables
- Dalvik Debug Monitor Service is one of most valuable tools for troubleshooting runtime
- also called DDMS
- to work with DDMS, chose device in devices view
- can take snapshot of screen in DDMS view by clicking snapshot in devices panel
- can also check memory usage
- select application in list and toggle update heap button in devices panel
- in ddms panel, select heap tab and Cause GC to cause garbage collection
- can then click on that event and look at details about how app is using memory at runtime
- in ddms panel, select heap tab and Cause GC to cause garbage collection
- select application in list and toggle update heap button in devices panel
- can also see what is happening in devices persistent storage in file explorer tab
- shows data storage for app and runtime
- if device isn’t rooted, or without root permission access, data folder is empty
- if device is rooted or emulator, you get to see subfolders and can see what is happening in data storage
- shows data storage for app and runtime
- Emulator control allows sending of data to emulator
- System info show data about processes and applications
- Once you have more than a single activity, must define how to move between them
- this is done with intent
- two kinds, explicit and implicit
- explicit intent say that wants to use specific activity
- implicit allows application framework to decide which intent to use
- two kinds, explicit and implicit
- this is done with intent
- current spec says we are supposed to let app handle its own navigation
- on secondary page, launcher icon should become up button
- Activity Lifecycle
- set of stages as they appear and disappear onscreen
- grouped into tasks
- when first opened
- launch activity is invoked (act. 1)
- this activity is part of task
- if this activity then launches act 2, it moves to top of stack and act. 1 moves down
- called going to backstack
- if back button is then pressed, or 2nd activity is finished, then 2nd act is removed and act. 1 comes to foreground
- when user hits home button and opens another application, second task is created, with it’s own activities
- user can switch between tasks from launcher screen or screen that lists all open tasks
- all activities are available if memory allows, but if not the OS can remove activities
- user can switch between tasks from launcher screen or screen that lists all open tasks
- Activity Stack rules
- on single device, only one active activity at any time
- if screen is in fragment view, many can be shown but only one is fully active
- one activity can be last active
- other activities are queued as previous activities
- can have as many in the backstack as necessary
- Activity can be in one of many states
- active/resumed – top of stack, visible and interactive
- paused – can be visible but without focus
- stopped – not visible, but not removed from memory
- inactive – completely removed from stack
- on single device, only one active activity at any time
- Lifecycle
- as activity comes to screen, it is created
- onCreate()
- then it is started
- onStart()
- then is is resumed, where it is visible and interactive
- onResume()
- as app is shut down, it goes into pause
- onPause()
- then it is stopped if it is to become invisible
- onStop()
- if removed from memory, then destroyed
- onDestroy()
- interesting event paths
- if in stop state and want to get to resume
- onRestart() to onStart() then to onResume()
- if paused, and want to get to resume
- onResume() event
- if in stop state and want to get to resume
- as activity comes to screen, it is created
- Loading and activity layout
- each lifecycle event is associated with a method
- example is onCreate() method
- setContentView loads layout
- example is onCreate() method
- each lifecycle event is associated with a method
- Each event that is triggered as move from activity to activity is associated with a method that are named for the event
- default version of methods are located in activity class or super class
- to add own code, must override methods
- brand new projects already have onCreate() method
- default version of methods are located in activity class or super class
- if android debug bridge (adb) is used to run apps on emulators and devices
- Device Market Fragmentation
- important to understand distribution of operating systems
- earliest version still in use if Frodo
- can find usage statistics at http://developers.android.com/about/dashboards
- it is difficult to go back to 2.2 levels, so it is acceptable to only code for version 4 (API 15) and above
- earliest version still in use if Frodo
- Biggest issue you have to deal with is screen sizes and pixel densities
- use dp and sp and create images with different sizes and resolutions for use with different pixel densities
- resizing images
- in res folder, notice multiple drawable folders (images folders) that map to different pixel densities
- mdpi – medium pixel density per inch
- xhdpi – high density
- xxhdpi – extra high
- graphic creation can be cumbersome in graphical application.
- there is an app called 9patch-resizer that does work for you
- code.google.com/p.9patch-resizer/
- this will allow you add drag images designed for certain pixel density
- ldpi (low) ~120dpi
- mdpi (medium) ~160dpi
- hdpi (high) ~240dpi
- xhdpi (extra-high) ~320dpi
- xxhdpi (extra-extra-high) ~480dpi
- xxxhdpi (extra-extra-extra-high) ~640dpi
- creates folders for each file in original folder, just copy and paste to res folder in Eclipse Project Explorer
- doesn’t remove anything currently there, just adds new files
- in res folder, notice multiple drawable folders (images folders) that map to different pixel densities
- rather than always creating multiple versions of graphics, will sometimes want to stretch graphic to screen sizes
- these are called 9patchDrawables
- these graphics have border set as stretchable region, and center set as no stretchable
- use tool for creating 9 patch drawable images
- open http://romannurik.github.io/AndroidAssetStudio/nine-patches.html
- must use chrome with tool
- open http://romannurik.github.io/AndroidAssetStudio/nine-patches.html
- these are called 9patchDrawables
- Launcher icons identify app on screen
- must be square, must start at 512 x 512, and must have some soft of transparency
- use this web address to create launcher icons
- http://romannurik.github.io/AndroidAssetStudio/icons-launcher.html
- make sure to create both launcher icon and web icon
- download zip, extract, copy, and paste into project folder
- make sure to create both launcher icon and web icon
- http://romannurik.github.io/AndroidAssetStudio/icons-launcher.html
- important to understand distribution of operating systems
- User Interface
- can control with widgets in layouts in layout file
- use styles to control appearance across multiple objects
- styles are set in XML files and applied, once defined can be reused
- beginning styles file is in values folder
- styles are set in XML files and applied, once defined can be reused
- themes
- default is holo light with dark action bar
- can update theme in activity manifest.xml on android:theme line
- use this syntax: android:theme=”@android:style/Theme.Black.NoTitleBar”
- Scrolling
- common issue is that sometimes there is too much content to fit on screen and user must be able to scroll text
- wrap content in scrolling container called scrollView
- common issue is that sometimes there is too much content to fit on screen and user must be able to scroll text
- Fragments
- in Honeycomb, fragments API gave more flexibility in laying out screen
- instead of one layout per screen, can use multiple layouts and be flexible on how they are laid out
- use eclipse android dev tools template to build adaptable application with fragments
- when creating new project, follow screens like normal but when getting to create activity screen, use master detail/flow
- has a list and a detail fragment
- on cell phone, start with list and then detail if item in list is selected while list goes away
- on tablet, two fragments are displayed side by side
- has a list and a detail fragment
- when creating new project, follow screens like normal but when getting to create activity screen, use master detail/flow
- in Honeycomb, fragments API gave more flexibility in laying out screen
- IMPORTANT TIP – on emulator, use CTRL + F12 to switch orientation of emulator display from portrait to landscape
- Events
- event handlers can be placed as attributes on widgets in layouts
- and example is a button which, when pressed, gives this code:
- android:onClick=”gotoActivity”
- android:onClick is event handler
- gotoActivity is method for event that is described in main activity java file
- android:onClick=”gotoActivity”
- can also make event handlers purely in java without event handlers in xml file
- more code but advantage is that everything is contained in one java file
- Handling system level events
- used with class called broadcast receiver
- 3 main steps
- 1 – Grant permission to application to deal with system level info
- 2 – create java class
- 3 – register java class
- 3 main steps
- used with class called broadcast receiver
- Orientation Changes
- when orientation changes, activity is destroyed and rebuilt from scratch on system
- many times, the OS can handle this change, however, sometimes will need to be personally tweaked to work correctly
- can control orientation change, by
- tell app in manifest that you don’t want automatic recreation
- add event handler in code
- can control orientation change, by
- and example is a button which, when pressed, gives this code:
- event handlers can be placed as attributes on widgets in layouts
- Options Menu
- menu that appears when options icon is touched
- position differs depending on device
- can be defined in XML or java code
- can define actions for application without taking up screen real estate
- menu that appears when options icon is touched
- Action bar
- introduced in Honeycomb and later device
- consists of area at top of screen with launcher icon, application name, and options menu if it exists
- we can add buttons to action bar by moving them from menu and placing them
- add this to each item in menu
- android:showAsAction=”always”
- different options for actions, use them wisely
- android:showAsAction=”always”
- add this to each item in menu
- can also add items to action bar at runtime
- every activity already has options menu, but is empty by default
- best practice is to define menu items in resources XML file, then use programming one activities where that menu item might be necessary
- Intent Extras
- as we move to more complex activities, will need to send and receive data between activities
- this is done with intent extras
- when returned to calling activity, these are called results
- in order to get information into activity, you must tell it you want that information in the first place
- do that with startActivityForResult
- in order to get information into activity, you must tell it you want that information in the first place
- Data lists
- as the data sent and returned becomes greater and greater, lists are a great way to organize information
- working with persistent data is critical, check out android sdk local data storage
- Next Steps
- learn more about android
- if I have question, always start with documentation, offline or online
- follow developer team blog
- android-developers.blogspot.com
- Ask Stack Overflow for tech support for android developers
- stackoverflow.com
- learn more XML integration with Java
- foundations of programming, object oriented design
- oop theory and practice
- learn more about android