1.21k likes | 2.17k Views
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
E N D
AndroidDevelopment 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 • Layoutsandother Views • Options Menu & Context Menu • Preferences • Services & Broadcast Receivers • … TODO MORE? …
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
Android SDK: Installation • Install the SDK starter package(Zip orinstallerfor Windows) • Add Android platforms and othercomponentsto your SDK.
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
Sample Application • Checkoutwithineclipse as Android project fromhttp://code.google.com/p/x-time/
Preferences • Createres/xml/preferences.xml file • Create Activity thatextendsPreferenceActivity • Define Activity in AndroidManifest.xml • Register listenertolaunch Activity • Get PreferencesusingPreferenceManager
FrameworkBasics • Views • Activities • Services • Content Providers • Intents & Intent Filters • Processes & Threads • Application Resources • Data Storage • Security & Permissions
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
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
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.
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.
Views: ApplyStyles and Themes • Createstyle.xml file in res/values/ bundlingproperties to a single selector (ref. CSS) • Referencestyle in layoutfiles, applystyle to a View
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
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)
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)
Activities: Interaction • DefineIntent Filters in manifest • StartanActivityfromanother • Addextra data • Start anActivityfor a result • StopanActivity
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
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
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
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)
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
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()
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
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
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)
Application Resources • Externaliseresources like images, text, … into/resdirectory • Improvesmaintainability • Defaultvsalternative resources (language, screen resolutions, target devices, …)
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
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
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
Data Storage • SharedPreferences • InternalStorage • ExternalStorage • SQLite Databases • NetworkConnection
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)
Data Storage: Internal • Files installedon the internaldevicememory • Bydefaultprivate to yourapplication, canbealteredusing MODE_WORLD_READABLE & WRITEABLE • UsingFileOutputStream
Data Storage: External • Removable (sd card) or non removableexternalstorageonyourdevice • Always check media availabilityusingEnvironment.getExternalStorageState()! • Get a File handlewithEnvironment.getExternalStorageDirectory()
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
Data Storage: NetworkConnection • Implementyourownserver for data storage • Check availability of network • Java.net.* and android.net.*packagesavailable
Security & Permissions • Bydefaultapplications have norights to update system, user orotherapps • Eachapplication runs in a sandbox • Developercangrantpermissionsusingdeclarations in manifest • User willbeprompteduponinstallation
Sample Application Demo
Test & Debug (ADB) • Update androidmanifest file forandroid:debuggable=“true” • Debugondeviceor via emulator • Walk throughjava code usingeclipsedebugperspective
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
Developer Console • https://market.android.com/publish/Home • Marketgraphics, screenshots, text • Statistics: devices, platform versions, countries, … • Errorreports + user comments • AppRating (stars) and Commnets
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/
Developer Resources • http://developer.android.com/ • http://Stackoverflow.com • http://android-developers.blogspot.com/ • http://xda-developers.com • Book: Learning Android
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/