1 / 49

Android Development

Android Development. Hans Cappelle & Jo Giraerts. Contents. Part 1: System Configuration Android SDK (ADK) Installation Eclipse IDE + ADT Installation Create & Launch Sample Application Part 2: X-Time Project Activities & Lifecycles Application Resources

asis
Download Presentation

Android Development

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. AndroidDevelopment Hans Cappelle & Jo Giraerts

  2. Contents • Part 1: System Configuration • Android SDK (ADK) Installation • Eclipse IDE + ADT Installation • Create & Launch Sample Application • Part 2: X-Time Project • Activities & Lifecycles • Application Resources • Layoutsandother Views • Options Menu & Context Menu • Preferences • Services & Broadcast Receivers • … TODO MORE? …

  3. Android SDK • The Android SDK provides the toolsand APIsnecessary to begin developingapplicationson the Android platform using the Java programminglanguage. • AvailableforWindows, OS X and Linux! • Allavailablefromhttp://d.android.com

  4. Android SDK: Installation • Install the SDK starter package(Zip orinstallerfor Windows) • Add Android platforms and othercomponentsto your SDK.

  5. Eclipse + ADT • Eclipse IDE availablefromhttp://www.eclipse.org. Choose the J2EE version. Download andunzip the package. • Installthe ADT PluginforEclipse(fromEclipse menu Help > Install Updates > add) from update site: https://dl-ssl.google.com/android/eclipse/ • InstallSubclipsepluginfrom update site: http://subclipse.tigris.org/update_1.8.x

  6. Sample Application • Checkoutwithineclipse as Android project fromhttp://code.google.com/p/x-time/

  7. Preferences • Createres/xml/preferences.xml file • Create Activity thatextendsPreferenceActivity • Define Activity in AndroidManifest.xml • Register listenertolaunch Activity • Get PreferencesusingPreferenceManager

  8. FrameworkBasics • Views • Activities • Services • Content Providers • Intents & Intent Filters • Processes & Threads • Application Resources • Data Storage • Security & Permissions

  9. Views • User interface is built usingView and ViewGroupobjects • All widgetsextend View class (ViewGroupextends View) • A complete UI exists of a hierarchyof View and ViewGroupnodes • Use .setContentView() method in Activity to attach view hierarchy to the screen

  10. Views: Hierarchy

  11. Views: XML Definition • XML offers a human-readablestructureforlayout (ref. HTML) • Each element in XML is a View (leaves)orViewGroup(branches)object (or descendant) • Use .addView(View) methods to dynamicallyinsertnew View and ViewGroupobjectsin Java code

  12. Views: XML Example

  13. Views: LayoutObjects (1) • FrameLayoutLayoutthat acts as a view frame to display a single object. • Gallery A horizontal scrolling display of images, from a bound list. • GridView Displays a scrollinggrid of m columns and nrows. • LinearLayout A layoutthatorganizesitschildreninto a single horizontal orverticalrow. Itcreates a scrollbarif the length of the windowexceeds the length of the screen. • ListView Displays a scrolling single column list. • RelativeLayoutEnablesyou to specify the location of childobjectsrelative to eachother (child A to the left of child B) or to the parent (aligned to the top of the parent). • ScrollView A verticallyscrolling column of elements.

  14. Views: LayoutObjects (2) • Spinner Displays a single item at a time from a bound list, inside a one-rowtextbox. Ratherlike a one-row listbox thatcan scroll eitherhorizontallyorvertically. • SurfaceView Provides direct access to a dedicateddrawingsurface. Itcanholdchild views layeredon top of the surface, but is intendedforapplicationsthatneed to draw pixels, ratherthanusingwidgets. • TabHost Provides a tab selection list that monitors clicks and enables the application to change the screen whenever a tab is clicked. • TableLayout A tabularlayoutwithanarbitrarynumber of rows and columns, eachcell holding the widget of yourchoice. The rowsresize to fit the largest column. The cell borders are notvisible. • ViewFlipper A list that displays one item at a time, inside a one-rowtextbox. Itcanbe set to swap items at timedintervals, like a slide show. • ViewSwitcherSame as ViewFlipper.

  15. Views: ApplyStyles and Themes • Createstyle.xml file in res/values/ bundlingproperties to a single selector (ref. CSS) • Referencestyle in layoutfiles, applystyle to a View

  16. Views: ApplyStyles and Themes • Styles and Themes support inheritance. Use the parentattribute • Stylescanbebundled in a Theme • Themescanbe set to anActivityoranApplicationusingandroid:themeattribute • Android comes withseveralplatform Stylesand Themes

  17. Activities • AnActivityrepresents a single screen • ManyActivitieslinkedtogetherformanapplication • MainActivity acts as entry point • OneActivitycan start another (withoptional extra data) • Activitystack(back stack), “last in - first out” queue • Activity has lifecyclecallbackmethods (oncreate, onresume, onpause, … defined in Activitysuperclass)

  18. Activities: Lifecycle

  19. Activities: Creation • ExtendActivitysuperclass • Set anXML layoutusing .setContentView() method • Implement user interface elements (Viewgroups& Views) • DeclareActivity in the Manifest (issue withrefactoring in eclipse, removes . if in subpackage = breaks code)

  20. Activities: Interaction • DefineIntent Filters in manifest • StartanActivityfromanother • Addextra data • Start anActivityfor a result • StopanActivity

  21. Services • Run long operations in the background • No User Interface (View) attached • Different lifecycle= different callbacks • A Service is Startedwhenanapplicationcompontentlaunchedit. The component itself does not have to continue. The Service will stop itselfoncefinished • A Service is Boundwhenit’sattached to one ore more Activities and willonly last as long as the activities • .onStartCommand() and .onBind() callbackmethods

  22. Services • StoppedfromanotherActivity/Service using.stopService() orbyitselfusing.stopSelf() • Extend Service and IntentServicesuperclass • Service class runs in same thread bydefault, don’tforget to start a thread! • IntentServicecreates a worker thread bydefault • Use service tag to defineyour service in manifest

  23. Services: LifeCycle

  24. Content Providers • Store and retrievedata betweenapplications • Providers forcommon data types (images, contacts, messages, …) bydefaultavailableon Android • Implementationhiddenafter single interface forquerying • AccessedindirectlyusingContentResolver(.getContentResolver()) • Data returned in Cursor as a table. Each entry has a unique_ID

  25. Content Providers • Each data type is exposedthrough a URI and starts withcontent:// • Query providers using .query() or .managedQuery() method.using arguments: • URI (withoptional _ID) • Name of the columns to return (array) • Whereclause (col_name=?) • Selectionarguments (array) • Sortorder (col_name asc/desc)

  26. Content Providers • HandleCursor data using .getXXX() methods • Add records usingContentValues(key-value pairs) and .insert() method • Update records in batch using .update() method • Delete records using .delete() method • Youcanimplement and exposeyourcustom providers

  27. Intents & Intent Filters • Intents are desigend to simplify the reuse of components; anyapplicationcanpublishitscapabilities and anyotherapplicationmayusethosecapabilities • Examples: Home replacements, Browsers, Contact managers, … • Activities, Services and BroadcastReceiversare activatedusingmessagesorIntents • Activity.startActivity() and .startActivityForResult() • Service.startService() and .bindService() • Context.sendBroadCast(), .sendOrderedBroadCast() and .sendStickyBroadcast()

  28. Intents & Intent Filters • AnIntent(object) is a passive data structure holding informationon the operation to execute • Use.putExtra()or.putExtras() to add extra information • Use.getExtras().getXXX()methods to retrievethisinformation • Intent Filters canbedefined to distinguishbetween different jobs Activities, Services and Broadcastscanhandle

  29. Processes & Threads • For eachApplicationstarted the system willcreate a separate processwith a single thread = The Main thread • Bydefaultall components of anActivity run in the sameProcess & Thread • In the manifest youcandefineanotherprocessforeach component usingandroid:processtag

  30. Processes & Threads • The main thread orUI thread is responsiblefor all widgets, includingdrawingevents & user eventhandling • Create separate WorkerThreadsto executingextensiveoperations (loading images, network, filesystem, …) • The Android UI Toolkitis not Thread Safe. Youcan’t update the UI formwithin a worker thread, use: • Activity.runOnUiThread(Runnable) • View.post(Runnable) • View.postDelayed(Runnable, long)

  31. Application Resources • Externaliseresources like images, text, … into/resdirectory • Improvesmaintainability • Defaultvsalternative resources (language, screen resolutions, target devices, …)

  32. Application Resources: Defaults • Anim/ foranimations • Color/ colorsfor fonts, backgrounds, etc • Drawable/ images • Layout/ xmllayoutdefinitions • Menu/ menu definitions • Raw/ usinginputstreams • Values/ simplevalues as string, integers, colors • Xml/ using .getXML() method

  33. Application Resources: Alternatives • Alternative resource qualifiersadded to folder name • Separatedwithdash(-), ex: res/drawable-hdpi/ • Somerulesapply: • Multiple qualifierspossible • Respect order of referencetable • Folders cannotbenested • Values are case insensitive • Onlyonevalueforeachqualifier type allowed

  34. Application Resources: Accessing • Oncompilation aapt generates the R classhaving resource ID’sfor all resources • Resource ID is composed of R.type.name, ex: R.string.hello • Reference in code usingR.string.hello • Reference in XML using @string/hello • Platform resources availablethroughandroid.R import

  35. Data Storage • SharedPreferences • InternalStorage • ExternalStorage • SQLite Databases • NetworkConnection

  36. Data Storage: SharedPreferences • .getSharedPreferences() for multiple preference files basedon name • .getPreferences() for a single preference file (no name required) • Store valuesusingSharedPreferences.Editor: .edit().putXXX(key,value).commit() • Retrievevaluesusing: .getXXX(key)

  37. Data Storage: Internal • Files installedon the internaldevicememory • Bydefaultprivate to yourapplication, canbealteredusing MODE_WORLD_READABLE & WRITEABLE • UsingFileOutputStream

  38. Data Storage: External • Removable (sd card) or non removableexternalstorageonyourdevice • Always check media availabilityusingEnvironment.getExternalStorageState()! • Get a File handlewithEnvironment.getExternalStorageDirectory()

  39. Data Storage: SQLite Database • Android shipswithhttp://www.sqlite.org support • ExtendSQLiteOpenHelperimplementing .onCreate() and .onUpgrade() methods • GetSQLiteDatabasehandlewith .getReadableDatabase() or .getWritableDatabase() • UseSQLiteDatabase.query() orSQLiteQueryBuilderto query data • UseCursor object to iteratefetched data

  40. Data Storage: NetworkConnection • Implementyourownserver for data storage • Check availability of network • Java.net.* and android.net.*packagesavailable

  41. Security & Permissions • Bydefaultapplications have norights to update system, user orotherapps • Eachapplication runs in a sandbox • Developercangrantpermissionsusingdeclarations in manifest • User willbeprompteduponinstallation

  42. Sample Application Demo

  43. Test & Debug (ADB) • Update androidmanifest file forandroid:debuggable=“true” • Debugondeviceor via emulator • Walk throughjava code usingeclipsedebugperspective

  44. Publishing • APK packagecontainsDalvikExecutables(.dex), optimizedfor minimal footprint • Update versionin manifest: android:versionName and android:versionCode • Packagename = marketid, set in manifest usingpackageattribute • SigningyourapplicationsusingEclipseplugin (orcommandlinetools) • UseDeveloper Console forupload and metadata

  45. Developer Console • https://market.android.com/publish/Home • Marketgraphics, screenshots, text • Statistics: devices, platform versions, countries, … • Errorreports + user comments • AppRating (stars) and Commnets

  46. Android + Arduino • Official Android ADK: http://www.engadget.com/2011/05/11/googles-arduino-based-adk-powers-robots-home-gardens-and-giant/ • Sparkfun IOIO board for Android: http://www.sparkfun.com/products/10585 • Other platforms fromcellbots: http://www.cellbots.com/http://www.diydrones.com/

  47. Developer Resources • http://developer.android.com/ • http://Stackoverflow.com • http://android-developers.blogspot.com/ • http://xda-developers.com • Book: Learning Android

  48. Customroms • http://feedproxy.google.com/~r/androidcentral/~3/1CKnfhd1dmU/sony-ericsson-teaches-how-build-and-flash-custom-kernel • http://www.cyanogenmod.com/ • http://www.xda-developers.com • http://feedproxy.google.com/~r/androidguyscom/~3/X4Z3fadiE1o/

More Related