Jumpstart to AndroidApp developmentLars Vogelhttp://www.vogella.deTwitter: @vogella
What is Android?FundamentalsConstructs of AndroidLive CodingQ&A
About me – Lars VogelIndependent Eclipse and Android consultant,trainer and book authorEclipse committerMaintains http://w...
More Android Sessions:Wednesday, 11.10 -12.00 - So whats so cool about Android 4.xThuersday – Friday – Full day Android tr...
Android Experience?
What isAndroid?
Android from 10 000 feet- Open Source- Full stack based on Linux- Java programming interface- Project is lead by Google- T...
On Android you develop in Java(There is also the NDK which allows development in C / C++...)
Overview of the API Capabilities Rich UI components Threads and Background Processing Full network stack (Http, JSON) Data...
Its likeprogramming forhardware which is10 years old
… with insameperformancerequirements
On Android you develop in JavaReally?
Android Programming You use the Java programming language but Android does not run Java Bytecode
DalvikRun Dalvik Executable Code (.dex)Tool dx converts Java Bytecode into .dex•   Register based VM vrs. stack based as t...
DeveloperToolchain
Android Development Tools (ADT)for EclipseEclipse based tooling• Provide the emulator• Wizard for creating new project• Ad...
Emulator           QEMU-based ARM emulator runs           same image as a device           Use same toolchain to work with...
Demo
AndroidManifest.xml• General configuration files for  your application• Contains all component  definitions of your appica...
Resources from /res areautomatically „indexed“
ADT maintains areference to allresources in the R.java
Main Android programming       constructs      Activity          Views             Intents                 Broadcast Recei...
Context
ContextGlobal information about an application environment.Allows access to application-specific resources and classesSupp...
DemoActivities project    Your first
ActivityExtends ContextAn activity is a single, focusedthing that the user can do.Kind of a screen but not entirely...
View vrs ViewGroupandroid.viewView: UI Widget - Button - TextView - EditText
Layoutsandroid.view.ViewGroup - Layout - extends View• Layouts are typically defined via XML  files (resources)• You can a...
Demo – Hello JFokus
Andoid isallowed to killyour app tosave memory.
Life Cyle of an Activityvoid onCreate(Bundle savedInstanceState)void onStart()void onRestart()void onResume()void onPause(...
States of an Activity• Active/ Running – Visible and interacts with user• Paused – still visible but partically obscured (...
To test flip your     device
Def    inin        gA          ctiv               itie                    s
Calling ActivitiesCalling Activitiescreates a stack ->Back button goesback to theprevious activity-> Think of it as astack...
Defining Activities• Create a class which extends  „Activitiy“• Create an entry in  „AndroidManifest.xml“ for the activity...
I had only thebest intents....
IntentsMessage passing mechanism to startActivities, Services or to trigger(system) events.Allow modular architectureCan c...
Intents • Explicit: Asking someone to do something • Implicit: Asking the system who can do something                   In...
Demo Intents
Implicit Intents• new Intent(Intent.ACTION_VIEW,  Uri.parse("http://www.vogella.de"));• new Intent(Intent.ACTION_CALL, Uri...
Gettings resultsIntent intent = newIntent("android.media.action.IMAGE_CAPTURE");startActivityForResult(intent, 0);public v...
XMLDrawables
XML Drawables• XML Resources• Can be used to define transitions,  shapes or state  A drawable resource is something  that ...
Services and receiver
ServicesAllow real multitasking and background processingDe-coupled from the Activity life-cyle
ServicesService runs in the background without interacting with the user.Android provides a multitude of system services• ...
Notification Manager  Demo
ServicesService runs in the background without interacting with the user.Android provides a multitude of system services• ...
Broadcast Receiver – Listen to events Example: BATTERY_LOW, ACTION_BOOT_COMPLETED android.intent.action.PHONE_STATE Define...
Own Service• Extend Service or IntentService• start with startService(Intent) or  bindService(Intent).• onStartCommand is ...
How to start a service Broadcast Receiver – Event: BOOT_COMPLETED Or ACTION_EXTERNAL_APPLICATIONS_A VAILABLE startService ...
Demo    alarmreceiver.phone
Security
Each apps gets into own Linux userand runs in its own process
Android Application requiresexplicit permissions, e.g. for• DB access•   Phone access•   Contacts•   Internet•   System me...
Background Processing
Be fast!Avoid ApplicationNotRespondingError
Use Threads (not the UI one)• Long running stuff should run in the  background• Thread cannot modify the UI• Synch with th...
Handler and AsyncTask• Handler runs in the UI thread• Allows to send Message object and or  to send Runnable to it      ha...
AsyncTask• To use it subclass itAsyncTask <TypeOfVarArgParams , ProgressValue ,ResultValue>doInBackground() – Do the worko...
Saving the thread• If a thread runs in your Activity you  want to save it.
Lifecycle - Thread• If Activity is destroyed the Threads should be  preserved.• Close down Dialogs in the onDestroy() meth...
Option Menus and       Action Bar
Option Menu & Action Bar• Option Menu displays if „Menu“  button is pressed• You can decided if the entries are  displayed...
Option Menu & Action Bar• Option Menu displays if „Menu“  button is pressed• You can decided if the entries are  displayed...
Preferences
Read and Write Preferences• Key – Value pairs• PreferenceManager.getDefaultShared  Preferences(this); – To read: getString...
PreferenceActivity• Create resource file (preference)• New Activity which extends  PreferenceActivity• To add preferences:...
ListView
ListViewCan be used to display a list of itemsGets his data from an adapter
Adapter                       Data for ListView                       defined by AdapterView per row definedby Adapter
ListActivityListActivity has already a predefined ListView with the id @android:id/listwhich will be used automatically.Pr...
What if the layout should     not be static?
Define your own Adapter
Reuse existing rowsIf convertView is not null -> reuse itSaves memory and CPU power (approx. 150 % faster according toGoog...
Views and Touch
There is more....
I havefeelings           Camera API           Motion Detection           Location API (GIS)           Heat Sensor         ...
Example Camera API
I can talk and     hearInternet (java.net, Apache HttpClient, JSON...)BluetoothEmailSMSVoIP (SIP (Session Initiation Proto...
Other CapabilitiesPush to deviceInteractive Widgets on the homescreenLive Wallpapers (as background)Animations and Styling...
Android 4.0
Whats so cool about Android 4.0?• Come to my talk on Wednesday... ;-)
SummaryAndroid powerful and well- designed development         platform   Easy to get started Power to the developer
Android: Where to go          from here:Android Introduction Tutorial   http://www.vogella.de/articles/Android/article.htm...
Thank youFor further questions:Lars.Vogel@gmail.comhttp://www.vogella.deTwitter http://www.twitter.com/vogellaGoogle+ http...
License &           Acknowledgements•   This work is licensed under the Creative Commons    Attribution-Noncommercial-No D...
Android Jumpstart Jfokus
Android Jumpstart Jfokus
Android Jumpstart Jfokus
Upcoming SlideShare
Loading in...5
×

Android Jumpstart Jfokus

2,672

Published on

Presentation at Jfokus about And

Published in: Technology, Education
0 Comments
7 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,672
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
153
Comments
0
Likes
7
Embeds 0
No embeds

No notes for slide

Android Jumpstart Jfokus

  1. 1. Jumpstart to AndroidApp developmentLars Vogelhttp://www.vogella.deTwitter: @vogella
  2. 2. What is Android?FundamentalsConstructs of AndroidLive CodingQ&A
  3. 3. About me – Lars VogelIndependent Eclipse and Android consultant,trainer and book authorEclipse committerMaintains http://www.vogella.de Java, Eclipseand Android related Tutorials with more then amillion visitors per month.
  4. 4. More Android Sessions:Wednesday, 11.10 -12.00 - So whats so cool about Android 4.xThuersday – Friday – Full day Android training
  5. 5. Android Experience?
  6. 6. What isAndroid?
  7. 7. Android from 10 000 feet- Open Source- Full stack based on Linux- Java programming interface- Project is lead by Google- Tooling available for Eclipse (and other IDEs)
  8. 8. On Android you develop in Java(There is also the NDK which allows development in C / C++...)
  9. 9. Overview of the API Capabilities Rich UI components Threads and Background Processing Full network stack (Http, JSON) Database available Images Access to the hardware (GPS, Camera, Phone) and much more............
  10. 10. Its likeprogramming forhardware which is10 years old
  11. 11. … with insameperformancerequirements
  12. 12. On Android you develop in JavaReally?
  13. 13. Android Programming You use the Java programming language but Android does not run Java Bytecode
  14. 14. DalvikRun Dalvik Executable Code (.dex)Tool dx converts Java Bytecode into .dex• Register based VM vrs. stack based as the JVM• .dex Files contain more then one class• Approx. 50 % of the size of a class file• op codes are two bytes instead of one in the JVM• As of Android 2.2 Dalvik JIT compiler• Primary engineer: Dan Bornstein
  15. 15. DeveloperToolchain
  16. 16. Android Development Tools (ADT)for EclipseEclipse based tooling• Provide the emulator• Wizard for creating new project• Additional Tooling, e.g views
  17. 17. Emulator QEMU-based ARM emulator runs same image as a device Use same toolchain to work with device or emulator Inital startup is slooooowwwwww.....
  18. 18. Demo
  19. 19. AndroidManifest.xml• General configuration files for your application• Contains all component definitions of your appication
  20. 20. Resources from /res areautomatically „indexed“
  21. 21. ADT maintains areference to allresources in the R.java
  22. 22. Main Android programming constructs Activity Views Intents Broadcast Receiver Services ContentProvider
  23. 23. Context
  24. 24. ContextGlobal information about an application environment.Allows access to application-specific resources and classesSupport application-level operations such as launchingactivities, broadcasting and receiving intents, etc.Basically all Android classes need a contextActivity extends Context
  25. 25. DemoActivities project Your first
  26. 26. ActivityExtends ContextAn activity is a single, focusedthing that the user can do.Kind of a screen but not entirely...
  27. 27. View vrs ViewGroupandroid.viewView: UI Widget - Button - TextView - EditText
  28. 28. Layoutsandroid.view.ViewGroup - Layout - extends View• Layouts are typically defined via XML files (resources)• You can assign properties to the layout elements to influence their behavior.
  29. 29. Demo – Hello JFokus
  30. 30. Andoid isallowed to killyour app tosave memory.
  31. 31. Life Cyle of an Activityvoid onCreate(Bundle savedInstanceState)void onStart()void onRestart()void onResume()void onPause()void onStop()void onDestroy()
  32. 32. States of an Activity• Active/ Running – Visible and interacts with user• Paused – still visible but partically obscured (other transparant activity, dialog or the phone screen), instance is running but might be killed by the system• Stopped – completely obscured, e.g. User presses the home screen button, instance is running but might be killed by the system• Killed – if stopped or paused, system might calling finish or by killing it
  33. 33. To test flip your device
  34. 34. Def inin gA ctiv itie s
  35. 35. Calling ActivitiesCalling Activitiescreates a stack ->Back button goesback to theprevious activity-> Think of it as astack of cards
  36. 36. Defining Activities• Create a class which extends „Activitiy“• Create an entry in „AndroidManifest.xml“ for the activity.• <activity android:name=“MyNewActivity“></a ctivity>
  37. 37. I had only thebest intents....
  38. 38. IntentsMessage passing mechanism to startActivities, Services or to trigger(system) events.Allow modular architectureCan contain data (extra)
  39. 39. Intents • Explicit: Asking someone to do something • Implicit: Asking the system who can do something Intent
  40. 40. Demo Intents
  41. 41. Implicit Intents• new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.vogella.de"));• new Intent(Intent.ACTION_CALL, Uri.parse("tel: (+49)12345789"));• new Intent(Intent.ACTION_VIEW, Uri.parse("geo:50.123,7.1434?z=19"));• new Intent("android.media.action.IMAGE_CAPTURE");
  42. 42. Gettings resultsIntent intent = newIntent("android.media.action.IMAGE_CAPTURE");startActivityForResult(intent, 0);public void onActivityResult(int requestCode, intresultCode, Intent data) { if (resultCode == Activity.RESULT_OK && requestCode== 0) { String result = data.toURI(); Toast.makeText(this, result, Toast.LENGTH_LONG); }}
  43. 43. XMLDrawables
  44. 44. XML Drawables• XML Resources• Can be used to define transitions, shapes or state A drawable resource is something that can be drawn to the screen
  45. 45. Services and receiver
  46. 46. ServicesAllow real multitasking and background processingDe-coupled from the Activity life-cyle
  47. 47. ServicesService runs in the background without interacting with the user.Android provides a multitude of system services• NotificationService• VibratorService• LocationService• AlarmService• ....Access via context.getSystemService(Context.CONST);You can define your own service for things that should run in thebackground
  48. 48. Notification Manager Demo
  49. 49. ServicesService runs in the background without interacting with the user.Android provides a multitude of system services• NotificationService• VibratorService• LocationService• AlarmService• ....Access via context.getSystemService(Context.CONST);You can define your own service for things that should run in thebackground
  50. 50. Broadcast Receiver – Listen to events Example: BATTERY_LOW, ACTION_BOOT_COMPLETED android.intent.action.PHONE_STATE Defined statically in manifest or temporary via code Broadcast Receiver only works within the onReceive() method C2DM
  51. 51. Own Service• Extend Service or IntentService• start with startService(Intent) or bindService(Intent).• onStartCommand is called in the service• bindService gets a ServiceConnection as parameter which receives a Binder object which can be used to communicate with the service
  52. 52. How to start a service Broadcast Receiver – Event: BOOT_COMPLETED Or ACTION_EXTERNAL_APPLICATIONS_A VAILABLE startService in the onReceiveMethod() Timer Service Start BroadcastReceiver which starts the service
  53. 53. Demo alarmreceiver.phone
  54. 54. Security
  55. 55. Each apps gets into own Linux userand runs in its own process
  56. 56. Android Application requiresexplicit permissions, e.g. for• DB access• Phone access• Contacts• Internet• System messages
  57. 57. Background Processing
  58. 58. Be fast!Avoid ApplicationNotRespondingError
  59. 59. Use Threads (not the UI one)• Long running stuff should run in the background• Thread cannot modify the UI• Synch with the UI thread runOnUiThread(new Runnable)
  60. 60. Handler and AsyncTask• Handler runs in the UI thread• Allows to send Message object and or to send Runnable to it handler.sendMessage(msg) handler.post(runnable)• AsyncTask for more complex work
  61. 61. AsyncTask• To use it subclass itAsyncTask <TypeOfVarArgParams , ProgressValue ,ResultValue>doInBackground() – Do the workonPostExecute() – Update the UI
  62. 62. Saving the thread• If a thread runs in your Activity you want to save it.
  63. 63. Lifecycle - Thread• If Activity is destroyed the Threads should be preserved.• Close down Dialogs in the onDestroy() method• One object can be saved via onRetainConConfigurationInstance()• Access via getLastNonConfigurationInstance()• Only use static inner classes in your Threads otherwise you create a memory leakage.
  64. 64. Option Menus and Action Bar
  65. 65. Option Menu & Action Bar• Option Menu displays if „Menu“ button is pressed• You can decided if the entries are displayed in the Action Bar or in a menu• Use „ifRoom“ flag if possible.
  66. 66. Option Menu & Action Bar• Option Menu displays if „Menu“ button is pressed• You can decided if the entries are displayed in the Action Bar or in a menu• Use „ifRoom“ flag if possible.
  67. 67. Preferences
  68. 68. Read and Write Preferences• Key – Value pairs• PreferenceManager.getDefaultShared Preferences(this); – To read: getString(key), get... – To change use edit(), putType(key, value), commit()• To maintain use PreferenceActivity
  69. 69. PreferenceActivity• Create resource file (preference)• New Activity which extends PreferenceActivity• To add preferences: – addPreferencesFromResource(R.xml.prefer ences);• Saving and edits will be handled automatically by the PreferenceActivity
  70. 70. ListView
  71. 71. ListViewCan be used to display a list of itemsGets his data from an adapter
  72. 72. Adapter Data for ListView defined by AdapterView per row definedby Adapter
  73. 73. ListActivityListActivity has already a predefined ListView with the id @android:id/listwhich will be used automatically.Provides nice method hooks for typical operations on listsIf you define your own layout this layout must contain a ListView with theID:@+android:id/list
  74. 74. What if the layout should not be static?
  75. 75. Define your own Adapter
  76. 76. Reuse existing rowsIf convertView is not null -> reuse itSaves memory and CPU power (approx. 150 % faster according toGoogle IO)Holder Pattern saves 25%
  77. 77. Views and Touch
  78. 78. There is more....
  79. 79. I havefeelings Camera API Motion Detection Location API (GIS) Heat Sensor Accelerator
  80. 80. Example Camera API
  81. 81. I can talk and hearInternet (java.net, Apache HttpClient, JSON...)BluetoothEmailSMSVoIP (SIP (Session Initiation Protocol))
  82. 82. Other CapabilitiesPush to deviceInteractive Widgets on the homescreenLive Wallpapers (as background)Animations and StylingSimple List handling(Multi-) TouchNFCCanvas / OpenGL ES (Game programming....)Native Rendering
  83. 83. Android 4.0
  84. 84. Whats so cool about Android 4.0?• Come to my talk on Wednesday... ;-)
  85. 85. SummaryAndroid powerful and well- designed development platform Easy to get started Power to the developer
  86. 86. Android: Where to go from here:Android Introduction Tutorial http://www.vogella.de/articles/Android/article.htmlOr Google for „Android Development Tutorial“Android SQLite and ContentProvider Bookhttp://www.amazon.com/dp/B006YUWEFEMore on Androidhttp://www.vogella.de/android.html
  87. 87. Thank youFor further questions:Lars.Vogel@gmail.comhttp://www.vogella.deTwitter http://www.twitter.com/vogellaGoogle+ http://gplus.to/vogella
  88. 88. License & Acknowledgements• This work is licensed under the Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Germany License – See http://creativecommons.org/licenses/by-nc-nd/3.0/de/deed.en_US
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×