Android Application Development Using Java


Published on

This is a simple and precise tutorial which lets anyone start developing mobile apps using android development platform.

Published in: Technology
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Android Application Development Using Java

  1. 1. Android ApplicationDevelopment using Java Amanullah
  2. 2. Web Apps vs. Mobile AppsWeb Apps, Pros• Advantages of Web Apps• Automatic “updates”• Well-established tools and methodologiesCons• Few and weak GUI controls• Cannot interact with local resources• Inefficient communication• Hard to write• Designed for large displays with mouse
  3. 3. Advantages of Mobile AppsMobile Apps, pros• Many GUI controls• Can interact with local resources• Efficient communication• Easier (?) to write• Designed for small displays with touch screenCons• No universal access• Difficult to manage updates• Newer (esp. Android)
  4. 4. Android Apps vs. iPhone AppsGeneric apps– iPhone has larger selection– Android trying to catch upIn-house-developed corporate appsiPhone apps can only be installed via the App StoreiPhone requires you to submit app to the Apple App Store and get approval, even for apps from your own company (Unless you jailbreak your phone)– Android apps can be installed through• Google App Store• Amazon App Store• USB connection from PC• Email• Corporate Web site
  5. 5. Languages for AppsiPhoneObjective-C• Similar to, but not exactly the same as, C++• Virtually no corporate presence for Objective-C, other than for mobile appsAndroid– Java ,The single most widely used language inside corporations– C/C++• Can call native apps (with some difficulty) via an approach similar to JNI for desktop Java
  6. 6. Operating Systems for Developing AppsiPhone– MacsAndroid– Anything with Java and Eclipse• Macs• PCs• Linux• SolarisPhone features, quality of apps, and coolness factors– Matter of opinion, but iPhone very strong here
  7. 7. Bottom Line:Which to use personally– iPhone has larger market share, bigger app store, and more loyal users– Android more open and growing more rapidly– Bottom line: no clear winner, personal preferences prevail, but iPhone has edgeWhich to use for in-house apps– iPhone apps very hard to install, Android simple– iPhone uses Objective C, Android uses Java– Bottom line: Android is clear winner
  8. 8. What is Android?• Android is a software stack for mobile devices.• Includes an operating system, middleware and key applications.• The Android SDK provides the tools and APIs necessary to begin developing applications.• Using the Java programming language.
  9. 9. Android Platform• Runs on top of Linux 2.6• Dalvik Virtual Machine optimized for mobile devices.• Integrated browser based on WebKit engine.• Optimized graphics with OpenGL ES.• SQLite database for structured data storage.
  10. 10. Android Versions• Android beta - November 5, 2007• Android 1.0 - September 23, 2008• Android 1.1- February 9, 2009• Cupcake 1.5- April 30, 2009• Donut 1.6- September 15, 2009• Éclair 2.0/2.1- October 26, 2009• Froyo 2.2.x- May 20, 2010• Gingerbread 2.3.x- December 6, 2010• Honeycomb 3.x- February 22, 2011• Ice Cream Sandwich 4.0.x- October 19, 2011• Jelly Bean- (expected version)
  11. 11. Get your PC readySupported Operating Systems• Windows XP or Vista• Mac OS X 10.4.8 or later (x86 only)• Linux (tested on Linux Ubuntu Dapper Drake)Supported Development Environments• Eclipse Integrated Development Environment (IDE)• Eclipse 3.5 (Galileo) Eclipse JDT plug-in (included in most Eclipse IDE packages)• JDK 5 or JDK 6• For developing Android applications, we recommend that you install one of these packages: Eclipse IDE for Java Developers
  12. 12. Install the SDK Starter Package• The SDK Starter Package is not a full development environment. It only includes the core SDK Tools, which you can use to download the rest of the SDK components.• Can be downloaded from
  13. 13. Install the ADT Plug-in for Eclipse• Android offers a custom Eclipse IDE plug-in called Android Development Tools (ADT) to give you a powerful, integrated environment in.• It allows – To let you quickly set up new Android projects – Create an application UI. – Debug your applications using the Android SDK tools – Even export signed (or unsigned) APKs in order to distribute your application. (Can be downloaded from where SDK is available)
  14. 14. Download and Add Platforms and Other ComponentsLaunch Android SDK and AVD Manager• From within Eclipse, select Window > Android SDK and AVD Manager.• On Windows, double-click the SDK Manager.exe file at the root of the Android SDK directory.
  15. 15. Use GUI of the Android SDK and AVD Manager to browse the SDKrepository and select new or updated components. AVD Manager SDK manager
  16. 16. Making Your Own Android App: BasicIdea– When you create a new app, it has simple “Hello World”functionality built in.• So, you can create and test an app without knowing syntax.Steps– File – New – Project – Android – Android Project• Once you do this once, next time you can do File – New – Android Project – Fill in options as shown on next page – Run new project as shown previouslyR-click – Run As – Android Application
  17. 17. Making Your Own Android App: Setting Project OptionsNew Android Project Settings– Project Name Eclipse project name.– Build Target The Android version that you want to use. Choose the most common version in use worldwide.– Application name Human-readable app name – title will be shown on Android title bar.– Package name– Create Activity The name of the top-level Java class– Min SDK Version Number to match the Build Target. But for details, see
  18. 18. Application Fundamentals• Applications written using Java Programming language.• Compiled into Android Package,(.apk).• Each app runs in its own sandbox and Linux process.• Apps consists of Components, a manifest file and resources. – Components • Activities • Services • Content providers • Broadcast receivers
  19. 19. Activities• Represents a single screen of UI.• Most apps contains multiple activities.• When new activity starts, it is pushed onto the Back Stack.• UI can be built using XML or Java.• Activity lifespan can be monitored using any of the call back methods link onStart(), onPause() etc.• You can respond to these methods using event handling.
  20. 20. Services• Perform long running background operations.• Doesn’t contain any UI.• Useful for operations like playing music, network operations etc.• Independent of the component that created it.• Can be bound to, by other application components, if allowed.
  21. 21. Content Providers• Used to store and receive data and make it accessible to all applications.• Are the only way to share data across applications.• Exposes a public URI that uniquely identifies its data set.• Data is exposed as a simple table on database model.• Android contains many content providers for things like contacts, media, etc.
  22. 22. Broadcast Receiver• Component that responds to system wide broadcast announcements.• Examples like screen turns off, battery low, etc.• Applications can initiate their own broadcasts.• Broadcast receivers contains no UI.• However they can create status bar notifications to alert the user.
  23. 23. Android Manifest file• All apps must have an AndroidManifest.xml file in its root directory.• Presents application information to the android system.• Describes components used in the application.• Declares permissions used to run the application.• Declares the minimum Android API level that the application needs.
  24. 24. Doesn’t make sense…An example follows now….
  25. 25. Hello world
  26. 26. Emulator• AVD manager allows to create a virtual device to test the apps.• Much similar to a real mobile phone to test all most all the features.• Device specific features are however not available.
  27. 27. Running app on emulatorBuiltin functionality– Newly created projects automatically have simple “Hello World” behavior.– Same as with any projectR-click - Run As – Android Applicaton– Reminder: do not close emulator after testing. Emulator takes a long time to start initially, but it is relatively fast to deploy a new or a changed project to the emulator.
  28. 28. FirstActivity.javapackage;import;import android.os.Bundle;public class FirstAppActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }}
  29. 29. main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /></LinearLayout>
  30. 30. AndroidManifest.xml<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="" package="" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".FirstAppActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
  31. 31.* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */package;public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040001; public static final int hello=0x7f040000; }}
  32. 32. Activities and XML together.• This app had a single screen on UI, so only one activity was used herein.• As discussed earlier, UI can be created using Java or XML (recommended), we used XML here.• We had and main.xml• Most apps have multiple screen on UI. – For every Activity we have a java file and an xml file. – One activity will call another and display the UI defined in xml file.
  33. 33. Seeing Standard Output in DDMSDDMS (Dalvik Debug Monitor Service) can • Simulate incoming calls in emulator • Set GPS locations in emulator • See print statements and runtime errors • Set locations and take screenshots of actual Android deviceSimple usage now Start DDMS Window - Open Perspective - DDMS
  34. 34. DDMS outputSee print statements• Look in LogCat window at bottom• Type part of output into Filter field to see specific outputCodePut System.out.println in main onCreate method• onCreate and other syntax discussed in next section
  35. 35. Running Apps on Physical Android DeviceThe vast majority of your testing will be on Android emulator. But sometimes you want to test on a physical phone or any Android device to test compatibility to use camera, GPS, contact list, etc.• You first make a signed application package (YourApp.apk), then you have options for sending it to the phone. – Connect phone via USB, use adb to deploy. – Submit app to Android marketplace – Email apk file to email address of phone – Deploy apk file to a Web site and connect using phone
  36. 36. Summary• Install software• Bookmark documentation• Update/configure software• Run apps – On emulator – On phone or device• Make new app• See output of print statements
  37. 37. Adding Resources to ProjectsWhy? – Internationalization, Localization – Different devices, have different screen sizes and different resolutions. – What fits in portrait orientation won’t fit in landscape – Images for high-density screens are too large for low- density onesSolutions… – Make multiple layout and resource files – For different languages, orientations, etc. – Have Android automatically switch among or combine them
  38. 38. Make versions of resource filesFind the settings that affect your application – Language, orientation, touchscreen type, dock mode, etc.Find qualifier names that correspond to each setting – Language: en, en-rUS, es, es-rMX, etc. – Screen orientation: port, land – Display density: xhdpi, hdpi, mdpi, ldpi – Dock mode: car, desk.Append qualifier names to folder names – res/values/strings.xml, res/values-es/strings.xml,res/values-es-rMX/main.xml – res/layout/main.xml, res/layout-land/main.xml
  39. 39. LanguagesResources that typically change– Strings (in res/values, e.g., in res/values/strings.xml)– Images (in res/drawable – image file or XML file)– Colors (in res/values, e.g., in res/values/colors.xml)– Audio and video (in res/raw)– Dimensions, arrays, and styles (in res/values, e.g…/dimens.xml, …/arrays.xml, …/styles.xml)Resources that do not usually change– Layout files (in res/layout)Changing layout based on language makes for hard-to maintain apps.
  40. 40. Put language-specific strings in language specific foldersIn res/values-es/strings.xml (or res/values-ja, etc), redefineonly the names that change based on language E.g., in res/values-es/strings.xml <string name="welcome_message">¡Bienvenidos!</string> No entry for company_name, since the company name does not change (in Spanish, it is still Apple, not Manzana) E.g., in res/values-ja/strings.xml <string name="welcome_message"> ようこそ! </string> No entry for company_name, since the company name does not change (in Japanese, it is still Apple, not アップル )
  41. 41. How to referIn XML, refer to base string name– someAttribute="@string/company_name"– someAttribute="@ string/welcome_message"No reference to folder or language.Android will provide the proper version automatically. It first loads values from res/values/strings.xml, then loads values from res/values-es/strings.xml.Any names in second file that are common to first file are replaced.• In Java, refer to base string name– getString(R.string.company_name)– getString(R.string.welcome_message)No reference to folder or language. Same process as above.• Use similar approach for other resources– XML: @drawable/flag, @color/default_foreground, etc.– Java: R.drawable.flag, R.color.default_foreground, etc.
  42. 42. Example (strings.xml)<?xml version="1.0" encoding="utf-8"?> (English)<resources><string name="resort_name"></string><string name="welcome">Welcome to </string><string name="our">Our </string><string name="pool">swimming pool</string><string name="reserve">Reserve Now!</string><string name="confirmed">Registration Confirmed</string></resources><?xml version="1.0" encoding="utf-8"?> (Spanish)<resources><string name="welcome">Bienvenido a </string><string name="our">Nuestra </string><string name="pool">piscina</string><string name="reserve">¡Reserva Ahora!</string><string name="confirmed">Registro Confirmado</string></resources>
  43. 43. Layout file (no language based versions)<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android=http://... android:orientation="vertical" ...><TextView android:text="@string/welcome" ... /><TextView android:text="@string/resort_name" ... />Manifest File (No Language-Based Versions)<manifest xmlns:android=""package="com.coreservlets.localization" android:versionCode="1"android:versionName="1.0"><uses-sdk android:minSdkVersion="8" /><application android:icon="@drawable/icon"android:label="@string/resort_name"><activity android:name=".AndroidResortActivity"android:label="@string/resort_name">
  44. 44. Screen OrientationOptions, Portrait and LandscapeResources that typically change– Layout files (in res/layout)– Images (in res/drawable – image file or XML file)– Dimensions (in res/values, e.g., …/dimens.xml)– Video (in res/raw)Resources that do not usually change– Strings (in res/values, e.g., in res/values/strings.xml)– Colors (in res/values, e.g., in res/values/colors.xml)– Audio (in res/raw)
  45. 45. StepsMake two folders: default and landscape res/layout, res/layout-landYou can do layout-port, but more common to use defaultDefine different layouts (of same name) in eachFor portrait mode res/layout/main.xml (or whatever)For landscape mode res/layout-land/main.xml (or whatever)Use similar approach for dimensions, images, etc.Use res/values/ and res/drawable for portrait mode andfor things that are the same in both orientations. Override in res/values-land and res/drawable-land
  46. 46. Event HandlingUsing a separate Listener class• Using a named inner class• Using an anonymous inner class• Using the main Activity– And having it implement the Listener interface• Using the main Activity– And specifying the method in the layout file (main.xml)
  47. 47. Using a Separate Listener ClassUse an external class that implements View.OnClickListenerImport android.view.View.OnClickListener, then say “implements OnClickListener”– You can pass arguments to change behavior– Separate classes generally promote loose couplingSo, if event handler can be applied to different controls, it can be change independently from rest of app.But, in most real situations, behavior is tightly coupled to app anyhow.
  48. 48. Using an Anonymous Inner ClassUse an anonymous inner class that implements the ListenerAssuming that each class is applied to a single control only, same advantages as named inner classes, but shorter.This approach is widely used in Swing, SWT, AWT, and GWTIf you applied the handler to more than one control, you would have to cut and paste the code for the handler.This approach should be applied for a single control only
  49. 49. Main Activity Implement ListenerHave the main Activity implement the Listener interface. Put the handler method in the main Activity. Call setOnClickListener(this).Assuming that the app has only a single control of that Listener type, this is the shortest and simplest of the approaches.
  50. 50. Specifying the Handler Method in main.xmlPut the handler method in the main Activity. Do not implement a Listener interface or call setOnClickListener. Have the layout file (main.xml) specify the handler method via the android:onClick attribute.
  51. 51. Screen Rotations and App restartsAndroid can shut down and restart your app– When you rotate the screen– When you change languages– When app is in background and Android is short on memory– When you hit the Back buttonSo?Save data in a Bundle in onSaveInstanceState– Read data out of Bundle in onRestoreInstanceState(or in onCreate)
  52. 52. SolutionOverride onSaveInstanceState– And pass the Bundle to the superclass methodprotected void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);outState.putBlah(someData);}Called when,– User rotates screen or changes language– When app is hidden and Android needs the memory– Not called when user hits Back button
  53. 53. Thanks for your attending