Android WorkshopGetting started with Android application development
About Myself      View slides @ http://www.slideshare.net/samwize
My Hobby Projects      just2us.com
My Hobby Projects                    Top App      just2us.com
My Full Time  developer.hoiio.com            View slides @ http://www.slideshare.net/samwize
Hoiio API    View slides @ http://www.slideshare.net/samwize
Hoiio APIMr Brown Podcast Over The Phone!!     Call 6602 8104                View slides @ http://www.slideshare.net/samwize
Android Apps: txeet         View slides @ http://www.slideshare.net/samwize
Android Apps: txeet                       ~250,000                      downloads
Android Apps: SG 4D         View slides @ http://www.slideshare.net/samwize
Android Apps: Hoiio Phone            View slides @ http://www.slideshare.net/samwize
Android Apps: Hoiio Chat            View slides @ http://www.slideshare.net/samwize
Contact Me• twitter @ samwize• Google+                      View slides @ http://www.slideshare.net/samwize
Schedule1. Introduction to Android2. Hands On 1 [45 min]3. Application Fundamentals & User Interfaces4. Hands On II [45 mi...
1. Introduction to Android
The Android OS• Linux Kernel• Write in Java code• Dalvik Virtual Machine• Application Framework• Ten billion apps download...
Android Architecture
Development Process
Platform Versions
2. Hands On I [45 min]
A couple of steps• Install SDK• Setup Emulator• Run Emulator• Create Project• Run Project
Install SDKs1. Install Eclipse - the IDE  http://www.eclipse.org/downloads/packages/eclipse-classic-371/indigosr12. Instal...
Setup Emulator• Add an AVD (Android Virtual Device) • Go to Windows > AVD Manager > Virtual    devices > New • Select Goog...
Setup Emulator
Run Emulator• In AVD Manager, select the newly created  AVD > Start
Run Emulator
Create Project• File > New > Android Project• Fill in: •   Project name •   Build target •   Application name •   Package ...
Create Project
Run Project• Run > Run as > Android Application
Run Project
Run on Actual Device• To run on actual Android device, connect  device to computer via USB• From device, go to Settings > ...
3. Application Fundamentals &         User Interface
Now that you see “Hello World”, let’s examine the project..
Project Structure
Project Structure                    R.drawable.icon                     R.layout.main                     R.string.hello
AndroidManifest.xml
Fundamentals• 4 main components: 1. Activity 2. Service 3. ContentProvider 4. BroadcastReceiver
Activity• Activity = Screen• An app is made up of multiple activities• Stack of activities/screens• Activity lifecycle
HelloWorldActivity
HelloWorldActivityActivity class has functions to handle onCreate, onResume, onPause, etc
Activity• Launch an Activity by calling  startActivity(intent)  Launch a known Activity  Intent intent = new Intent(this, ...
Activity• Launch an Activity by calling  startActivity(intent)  Launch a known Activity  Intent intent = new Intent(this, ...
Activity•   Activity must be declared in AndroidManifest.xml    <manifest ... >      <application ... >          <activity...
Service•   Service runs in the background, even when user is not    interacting with your app•   Service or Thread ?•   To...
ContentProvider• A way to share data across applications,   including apps such as phonebook,   calendar, etc.• In other w...
BroadcastReceiver• Responds to system-wide broadcast  announcements such as incoming phone  call, SMS sent, picture captur...
User Interfaces                  Slides on http://www.slideshare.net/samwize
View Hierarchy1. View - Android UI component, view or widget2. ViewGroup - Layout or container view
View• UI components can be found in    android.widget package•   Basic UI:    •   TextView    •   Button    •   TextField ...
ViewGroupLinearLayout
ViewGroupTableLayout
ViewGroupRelativeLayout
User Interfaces• 2 ways to construct UI 1. XML 2. Code
The way of XML                         /res/layout/main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:andro...
The way of XML                         /res/layout/main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:andro...
The way of XML                         /res/layout/main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:andro...
The way of XML                         /res/layout/main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:andro...
The way of XML                         /res/layout/main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:andro...
The way of Codepackage com.just2us.helloandroid;import android.app.Activity;import android.os.Bundle;import android.widget...
The way of Codepackage com.just2us.helloandroid;import android.app.Activity;import android.os.Bundle;import android.widget...
The way of Codepackage com.just2us.helloandroid;import android.app.Activity;import android.os.Bundle;import android.widget...
The way of Codepackage com.just2us.helloandroid;import android.app.Activity;import android.os.Bundle;import android.widget...
4. Hands On II [45 min]
1) Linear Layout• Follow tutorial from:  http://developer.android.com/resources/  tutorials/views/hello-linearlayout.html
2) Form Stuff• Follow tutorial from:  http://developer.android.com/resources/  tutorials/views/hello-formstuff.html
More tutorial..• “Hello View” tutorials    •   http://developer.android.com/resources/tutorials/views/index.html•   “Api D...
5. Advanced TopicsPreferences, Database, Network, Multimedia
Preferences• The easiest way to store information• NOT only store preferences/settings, but  also arbitrary key-value pair...
Preferencespublic class Calc extends Activity {    public static final String PREFS_NAME = "MyPrefsFile";    @Override    ...
Database• Tabular data• SQLite behind the scenes• Extend SQLiteOpenHelper
Databasepublic class DictionaryOpenHelper extends SQLiteOpenHelper {        private   static final int DATABASE_VERSION = ...
Database• Call getWritableDatabase() or  getReadableDatabase() to get an  SQLiteDatabase object• With SQLiteDatabase, call...
Network• Connect to web services over HTTP• Permission needed in Manifest  <uses-permission android:name="android.permissi...
Network - GETHttpClient client = new DefaultHttpClient();HttpGet request = new HttpGet("http://www.myserver.com/script1.ph...
Network - POSTHttpClient client = new DefaultHttpClient();HttpPost request = new HttpPost("http://www.myserver.com/login_s...
Multimedia• Camera• Playback audio and video
Multimedia - Camera<uses-permission android:name="android.permission.CAMERA" /><uses-feature android:name="android.hardwar...
Multimedia - Camera• 2 ways to capture photo • Using capture intent • Using Camera class directly
Multimedia - Cameraprivate static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;private Uri fileUri;@Overridepublic ...
Multimedia - Cameraprivate static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;private Uri fileUri;@Overridepublic ...
Multimedia - Cameraprivate static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;private Uri fileUri;@Overridepublic ...
Multimedia - Cameraprivate static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;private static final int CAPTURE_VID...
Multimedia - MediaPlayer• Play audio and video from: • /res/raw/ • File system (internal or external) • Stream over Intern...
Multimedia - MediaPlayer<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="andro...
Multimedia - MediaPlayerMediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);mediaPlayer.start();...m...
Multimedia - MediaPlayerString url = "http://........"; // your streaming URL hereMediaPlayer mediaPlayer = new MediaPlaye...
Multimedia - MediaPlayer• Playing video is similar to audio• Pass a SurfaceHolder (view class) which the  MediaPlayer can ...
6. What’s next?
More Topics• Location (GPS) and Map• Bluetooth• USB host and accessory• Animation• OpenGL ES
Arduino & Bluetooth
Notepad Tutorial• Exercise 1- ListActivity and database  http://developer.android.com/resources/tutorials/notepad/notepad-...
Sample Code• Sample Codes  http://developer.android.com/resources/samples/get.html• API Demo, Bluetooth Chat, News Reader,...
User Interfaces• Supporting different screen sizes  http://developer.android.com/guide/practices/screens_support.html• Com...
Change view on a set of data
Select multiple items
Dashboard
Important Resources• http://developer.android.com• http://stackoverflow.com/• http://www.google.com/
Android Workshop
Android Workshop
Android Workshop
Upcoming SlideShare
Loading in...5
×

Android Workshop

2,280

Published on

Android Workshop for NTU. A getting started guide to android application development.

UPDATE (Oct 2013): An updated slide at http://samwize.com/2013/10/13/android-workshop-2013/

Published in: Technology
3 Comments
5 Likes
Statistics
Notes
No Downloads
Views
Total Views
2,280
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
3
Likes
5
Embeds 0
No embeds

No notes for slide
  • 4-hour Android workshop\nGet started\nZero Android, but some programming knowledge\n\nFor NTU School of EEE, Design &amp; Innovation Project (DIP)\n12 teams (of 10 members)\nhttp://www.eee.ntu.edu.sg/events/Design%20and%20Innovation%20Project/Pages/Introduction.aspx\n
  • Get to know me, my experience\nFor you to ask relevant questions\nEven as a consultant to your projects\nDOWNLOAD the slides\n
  • write lots mobile apps\nStarted with WAP &gt; Java ME &gt; BB &gt; iPhone &gt; Android &gt; WP7\nSkipped Symbian.. \nMy hobby apps, now..\n
  • write lots mobile apps\nStarted with WAP &gt; Java ME &gt; BB &gt; iPhone &gt; Android &gt; WP7\nSkipped Symbian.. \nMy hobby apps, now..\n
  • write lots mobile apps\nStarted with WAP &gt; Java ME &gt; BB &gt; iPhone &gt; Android &gt; WP7\nSkipped Symbian.. \nMy hobby apps, now..\n
  • Hoiio, startup\nEx-mobile lead\nAPI Lead, developer product\n\n
  • \n
  • Voice/SMS for your project\n
  • Some of my Android apps\nSecret to do this that\nSMS template app\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Android as an OS\nHands On Coding, and break if done\nGuidance to life after this 4hr\n
  • Fun Company\nGreen robot\nFav desserts\nhttp://developer.android.com/guide/basics/what-is-android.html\nhttp://kschang.hubpages.com/slide/Cupcake-Donut-Eclair-Froyo-Gingerbread-Honeycomb-Android-OS-Version-Codenames-and-Why/4609964\n
  • Android is everywhere - Phones, tablets, Google TV. Future: Cars, tanks.\nPhone - most prevalent. A device with lots of I/O. Also small.\n\n
  • Android != Linux\nUsed Linux security, mem mgmt, threading, etc\nEach app, 1 VM instance\nOptimized for mobile\nAndroid Package. A zip. Like Jar.\nApplication Framework = APIs - Storage, Network, Multimedia, GPS, Phone services (see next)\n
  • An open development platform.\n4 Abstraction layers\nAndroid offers developers the ability to build extremely rich and innovative applications - take advantage of the device hardware, etc\nDevelopers have full access to the same framework APIs used by the core applications. \nThe application architecture is designed to simplify the reuse of components. allows components to be replaced by the user.\nhttp://developer.android.com/guide/basics/what-is-android.html\n
  • http://developer.android.com/guide/developing/index.html\n
  • http://developer.android.com/resources/dashboard/platform-versions.html\n
  • Hello World!\nGo thru slides first, quickly - reference\nDemo once first\n
  • I will go through the steps first. Show it to you. Then you try out.\n
  • Tools, compiler, emulators\n
  • \n
  • \n
  • \n
  • \n
  • http://developer.android.com/resources/tutorials/hello-world.html\n
  • http://developer.android.com/resources/tutorials/hello-world.html\n
  • http://developer.android.com/resources/tutorials/hello-world.html\n
  • DDMS, LogCat\nDebugging!\n
  • \n
  • http://developer.android.com/guide/topics/fundamentals.html\n
  • \n
  • All files under res are parsed and accessible in code by eg. R.layout.main and R.drawable.icon\n
  • All files under res are parsed and accessible in code by eg. R.layout.main and R.drawable.icon\n
  • All files under res are parsed and accessible in code by eg. R.layout.main and R.drawable.icon\n
  • All files under res are parsed and accessible in code by eg. R.layout.main and R.drawable.icon\n
  • All files under res are parsed and accessible in code by eg. R.layout.main and R.drawable.icon\n
  • All files under res are parsed and accessible in code by eg. R.layout.main and R.drawable.icon\n
  • All files under res are parsed and accessible in code by eg. R.layout.main and R.drawable.icon\n
  • Foundation for an app is contained in this xml - the activities, services, intents, and so on. \nWhich activity appear on device&amp;#x2019;s launcher\nApp name, icon, etc\n
  • Activity - A single screen (UI)\nService - background activity eg. play music globally\nContentProvider - Even share data across apps. SQLite. eg. contacts. ContentResolver\nBroadcastReceiver - Responds to system wide broadcast announcements. Usually from the system eg. Send Message, Picture captured\n\nhttp://developer.android.com/guide/topics/fundamentals.html\n
  • It is a screen/window to draw your UI.\nAn app makes up of 1 or more activities\nScreens stack up. When BACK is pressed, the top screen is removed, and the one below is shown. \nFIFO\nhttp://developer.android.com/guide/topics/fundamentals/activities.html\n
  • Activity lifecycle\nPause - a call comes in, a notification is shown over the screen\nStop - screen is no longer visible\n
  • \n
  • \n
  • In an Activity class, call startActivity with an Intent.\nConcept of intent\nA few different ways to construct the intent.\n
  • \n
  • Thread, does NOT run when app is in background\nhttp://developer.android.com/guide/topics/fundamentals/services.html\n\n
  • http://developer.android.com/guide/topics/providers/content-providers.html\nhttp://developer.android.com/reference/android/provider/package-summary.html\n
  • http://developer.android.com/reference/android/content/BroadcastReceiver.html\n
  • http://developer.android.com/guide/topics/fundamentals.html\n
  • http://developer.android.com/resources/tutorials/views/index.html\n
  • ViewGroup contains 1 or more View\n
  • http://developer.android.com/reference/android/widget/package-summary.html \nhttp://developer.android.com/reference/android/view/View.html\nhttp://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/index.html\n\n
  • http://developer.android.com/guide/topics/ui/layout-objects.html \n
  • http://developer.android.com/guide/topics/ui/layout-objects.html \n
  • http://developer.android.com/guide/topics/ui/layout-objects.html \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • API Demo has several small &amp;#x2018;applications&amp;#x2019; to illustrate different APIs, including UI widgets. The holy demo app to install.\n
  • \n
  • http://developer.android.com/reference/android/content/SharedPreferences.html\nhttp://developer.android.com/guide/topics/data/data-storage.html#pref\nPreferenceActivity: http://developer.android.com/reference/android/preference/PreferenceActivity.html\n
  • Call edit() from sharedPreferences\nputBoolean\ncommit - thread safe transactions\n
  • \n
  • \n
  • \n
  • Eg. Facebook API, yahoo weather API, connects to your backend, etc\nMore permissions: http://developer.android.com/reference/android/Manifest.permission.html\n
  • http://developer.android.com/reference/org/apache/http/client/HttpClient.html\n
  • http://developer.android.com/reference/org/apache/http/client/HttpClient.html\n
  • Camera for taking photo or video\n
  • http://developer.android.com/guide/topics/media/camera.html\nPermission and feature in manifest again\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • http://developer.android.com/guide/topics/media/mediaplayer.html\nhttp://developer.android.com/reference/android/media/MediaPlayer.html\n
  • \n
  • \n
  • \n
  • \n
  • Life after this 4hr workshop, is long ahead..\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Android Workshop

    1. 1. Android WorkshopGetting started with Android application development
    2. 2. About Myself View slides @ http://www.slideshare.net/samwize
    3. 3. My Hobby Projects just2us.com
    4. 4. My Hobby Projects Top App just2us.com
    5. 5. My Full Time developer.hoiio.com View slides @ http://www.slideshare.net/samwize
    6. 6. Hoiio API View slides @ http://www.slideshare.net/samwize
    7. 7. Hoiio APIMr Brown Podcast Over The Phone!! Call 6602 8104 View slides @ http://www.slideshare.net/samwize
    8. 8. Android Apps: txeet View slides @ http://www.slideshare.net/samwize
    9. 9. Android Apps: txeet ~250,000 downloads
    10. 10. Android Apps: SG 4D View slides @ http://www.slideshare.net/samwize
    11. 11. Android Apps: Hoiio Phone View slides @ http://www.slideshare.net/samwize
    12. 12. Android Apps: Hoiio Chat View slides @ http://www.slideshare.net/samwize
    13. 13. Contact Me• twitter @ samwize• Google+ View slides @ http://www.slideshare.net/samwize
    14. 14. Schedule1. Introduction to Android2. Hands On 1 [45 min]3. Application Fundamentals & User Interfaces4. Hands On II [45 min]5. Advanced Topics - Preferences, Database, Network, Multimedia6. What’s next? View slides @ http://www.slideshare.net/samwize
    15. 15. 1. Introduction to Android
    16. 16. The Android OS• Linux Kernel• Write in Java code• Dalvik Virtual Machine• Application Framework• Ten billion apps downloaded!
    17. 17. Android Architecture
    18. 18. Development Process
    19. 19. Platform Versions
    20. 20. 2. Hands On I [45 min]
    21. 21. A couple of steps• Install SDK• Setup Emulator• Run Emulator• Create Project• Run Project
    22. 22. Install SDKs1. Install Eclipse - the IDE http://www.eclipse.org/downloads/packages/eclipse-classic-371/indigosr12. Install Android SDK http://developer.android.com/sdk/index.html3. Install Android ADT Plugin for Eclipse http://developer.android.com/sdk/eclipse-adt.html#installing Guide from http://developer.android.com/sdk/installing.html
    23. 23. Setup Emulator• Add an AVD (Android Virtual Device) • Go to Windows > AVD Manager > Virtual devices > New • Select Google APIs - API Level 10 as target (which is v2.3.3)
    24. 24. Setup Emulator
    25. 25. Run Emulator• In AVD Manager, select the newly created AVD > Start
    26. 26. Run Emulator
    27. 27. Create Project• File > New > Android Project• Fill in: • Project name • Build target • Application name • Package name • Activity • Min SDK Version
    28. 28. Create Project
    29. 29. Run Project• Run > Run as > Android Application
    30. 30. Run Project
    31. 31. Run on Actual Device• To run on actual Android device, connect device to computer via USB• From device, go to Settings > Applications > Development > enabled USB debugging• Run project
    32. 32. 3. Application Fundamentals & User Interface
    33. 33. Now that you see “Hello World”, let’s examine the project..
    34. 34. Project Structure
    35. 35. Project Structure R.drawable.icon R.layout.main R.string.hello
    36. 36. AndroidManifest.xml
    37. 37. Fundamentals• 4 main components: 1. Activity 2. Service 3. ContentProvider 4. BroadcastReceiver
    38. 38. Activity• Activity = Screen• An app is made up of multiple activities• Stack of activities/screens• Activity lifecycle
    39. 39. HelloWorldActivity
    40. 40. HelloWorldActivityActivity class has functions to handle onCreate, onResume, onPause, etc
    41. 41. Activity• Launch an Activity by calling startActivity(intent) Launch a known Activity Intent intent = new Intent(this, SignInActivity.class); startActivity(intent);
    42. 42. Activity• Launch an Activity by calling startActivity(intent) Launch a known Activity Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); Launch a system Activity Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); startActivity(intent);
    43. 43. Activity• Activity must be declared in AndroidManifest.xml <manifest ... >   <application ... >       <activity android:name=".HelloWorldActivity" />       ...   </application ... >   ... </manifest >
    44. 44. Service• Service runs in the background, even when user is not interacting with your app• Service or Thread ?• To start, call startService()• Similar to Activity, has its lifecycle and various event callbacks
    45. 45. ContentProvider• A way to share data across applications, including apps such as phonebook, calendar, etc.• In other words, you can access the phonebook using a ContentProvider• Have query, insert, delete methods (SQLite)ContentResolver cr = getContentResolver();cr.query(“content://android.provider.Contacts.Phones.CONTACT_URI”, projection, selection, selectionArg, sortOrder)
    46. 46. BroadcastReceiver• Responds to system-wide broadcast announcements such as incoming phone call, SMS sent, picture captured, etc
    47. 47. User Interfaces Slides on http://www.slideshare.net/samwize
    48. 48. View Hierarchy1. View - Android UI component, view or widget2. ViewGroup - Layout or container view
    49. 49. View• UI components can be found in android.widget package• Basic UI: • TextView • Button • TextField • Progress bar • List • etc..
    50. 50. ViewGroupLinearLayout
    51. 51. ViewGroupTableLayout
    52. 52. ViewGroupRelativeLayout
    53. 53. User Interfaces• 2 ways to construct UI 1. XML 2. Code
    54. 54. The way of XML /res/layout/main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /></LinearLayout>
    55. 55. The way of XML /res/layout/main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /></LinearLayout> looks in /res/values/string.xml, and find the value for the key “hello”
    56. 56. The way of XML /res/layout/main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /></LinearLayout> Equivalently.. android:text="Hello world too!"
    57. 57. The way of XML /res/layout/main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /></LinearLayout> @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }
    58. 58. The way of XML /res/layout/main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /></LinearLayout> @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } setContentView() inflate main.xml and set the views
    59. 59. The way of Codepackage com.just2us.helloandroid;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class HelloAndroid extends Activity {   /** Called when the activity is first created. */   @Override   public void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);       TextView textview = new TextView(this);       textview.setText("Hello, Android");       setContentView(textview);   }}
    60. 60. The way of Codepackage com.just2us.helloandroid;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class HelloAndroid extends Activity {   /** Called when the activity is first created. */   @Override   public void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);       TextView textview = new TextView(this);       textview.setText("Hello, Android");       setContentView(textview);   }} Creating a TextView and set the text
    61. 61. The way of Codepackage com.just2us.helloandroid;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class HelloAndroid extends Activity {   /** Called when the activity is first created. */   @Override   public void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);       TextView textview = new TextView(this);       textview.setText("Hello, Android");       setContentView(textview);   }} Similarly to the way of XML, setContentView()
    62. 62. The way of Codepackage com.just2us.helloandroid;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class HelloAndroid extends Activity {   /** Called when the activity is first created. */   @Override   public void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);       TextView textview = new TextView(this);       textview.setText("Hello, Android");       setContentView(textview);   }}
    63. 63. 4. Hands On II [45 min]
    64. 64. 1) Linear Layout• Follow tutorial from: http://developer.android.com/resources/ tutorials/views/hello-linearlayout.html
    65. 65. 2) Form Stuff• Follow tutorial from: http://developer.android.com/resources/ tutorials/views/hello-formstuff.html
    66. 66. More tutorial..• “Hello View” tutorials • http://developer.android.com/resources/tutorials/views/index.html• “Api Demo” sample code • http://developer.android.com/resources/samples/ApiDemos/ index.html
    67. 67. 5. Advanced TopicsPreferences, Database, Network, Multimedia
    68. 68. Preferences• The easiest way to store information• NOT only store preferences/settings, but also arbitrary key-value pairs• SharedPreference class• getBoolean, setBoolean, etc..
    69. 69. Preferencespublic class Calc extends Activity {    public static final String PREFS_NAME = "MyPrefsFile";    @Override    protected void onCreate(Bundle state){       super.onCreate(state);       // Restore preferences       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);       boolean silent = settings.getBoolean("silentMode", false);       setSilent(silent);    }    @Override    protected void onStop(){       super.onStop();      // We need an Editor object to make preference changes.      // All objects are from android.context.Context      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);      SharedPreferences.Editor editor = settings.edit();      editor.putBoolean("silentMode", mSilentMode);      // Commit the edits!      editor.commit();    }}
    70. 70. Database• Tabular data• SQLite behind the scenes• Extend SQLiteOpenHelper
    71. 71. Databasepublic class DictionaryOpenHelper extends SQLiteOpenHelper {    private static final int DATABASE_VERSION = 2;    private static final String DICTIONARY_TABLE_NAME = "dictionary";    private static final String DICTIONARY_TABLE_CREATE =                "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +                KEY_WORD + " TEXT, " +                KEY_DEFINITION + " TEXT);";    DictionaryOpenHelper(Context context) {        super(context, DATABASE_NAME, null, DATABASE_VERSION);    }    @Override    public void onCreate(SQLiteDatabase db) {        db.execSQL(DICTIONARY_TABLE_CREATE);    }}
    72. 72. Database• Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object• With SQLiteDatabase, call query() to execute SQL queries
    73. 73. Network• Connect to web services over HTTP• Permission needed in Manifest <uses-permission android:name="android.permission.INTERNET" />• A few different ways to connect• HttpClient is most robust
    74. 74. Network - GETHttpClient client = new DefaultHttpClient();HttpGet request = new HttpGet("http://www.myserver.com/script1.php");// Execute HTTP GET request and get responseHttpResponse response = client.execute(request);InputStream is = response.getEntity().getContent();BufferedReader in = new BufferedReader(new InputStreamReader(is));// Do what you need with content StringBuffer sb = new StringBuffer("");String line = "";String NL = System.getProperty("line.separator");while ((line = in.readLine()) != null) { sb.append(line + NL);}in.close();String content = sb.toString();// Do what you need with content...
    75. 75. Network - POSTHttpClient client = new DefaultHttpClient();HttpPost request = new HttpPost("http://www.myserver.com/login_script.php");// Add your dataList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);nameValuePairs.add(new BasicNameValuePair("username", "samwize"));nameValuePairs.add(new BasicNameValuePair("password", "123456"));request.setEntity(new UrlEncodedFormEntity(nameValuePairs));// Execute HTTP POST RequestHttpResponse response = httpclient.execute(request);       
    76. 76. Multimedia• Camera• Playback audio and video
    77. 77. Multimedia - Camera<uses-permission android:name="android.permission.CAMERA" /><uses-feature android:name="android.hardware.camera" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.RECORD_AUDIO" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    78. 78. Multimedia - Camera• 2 ways to capture photo • Using capture intent • Using Camera class directly
    79. 79. Multimedia - Cameraprivate static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;private Uri fileUri;@Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);    // create Intent to take a picture and return control to the calling application    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name    // start the image capture Intent    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);} Capture photo
    80. 80. Multimedia - Cameraprivate static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;private Uri fileUri;@Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);    //create new Intent    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);    fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);  // create a file to save the video    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  // set the image file name    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high    // start the Video Capture Intent    startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);}
    81. 81. Multimedia - Cameraprivate static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;private Uri fileUri;@Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);    //create new Intent    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);    fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);  // create a file to save the video    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  // set the image file name    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high    // start the Video Capture Intent    startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);} Capture video
    82. 82. Multimedia - Cameraprivate static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {        if (resultCode == RESULT_OK) {            // Image captured and saved to fileUri specified in the Intent            Toast.makeText(this, "Image saved to:n" +                     data.getData(), Toast.LENGTH_LONG).show();        } else if (resultCode == RESULT_CANCELED) {            // User cancelled the image capture        } else {            // Image capture failed, advise user        }    }    if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {        if (resultCode == RESULT_OK) {            // Video captured and saved to fileUri specified in the Intent            Toast.makeText(this, "Video saved to:n" +                     data.getData(), Toast.LENGTH_LONG).show();        } else if (resultCode == RESULT_CANCELED) {            // User cancelled the video capture        } else {            // Video capture failed, advise user        }    }} Handling after photo/video is captured by camera app
    83. 83. Multimedia - MediaPlayer• Play audio and video from: • /res/raw/ • File system (internal or external) • Stream over Internet• MediaPlayer class
    84. 84. Multimedia - MediaPlayer<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.WAKE_LOCK" />
    85. 85. Multimedia - MediaPlayerMediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);mediaPlayer.start();...mediaPlayer.stop(); Playing /res/raw/sound_file_1.mp3
    86. 86. Multimedia - MediaPlayerString url = "http://........"; // your streaming URL hereMediaPlayer mediaPlayer = new MediaPlayer();mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);mediaPlayer.setDataSource(url);mediaPlayer.prepare(); // might take long! (for buffering, etc)mediaPlayer.start(); Playing audio stream from Internet
    87. 87. Multimedia - MediaPlayer• Playing video is similar to audio• Pass a SurfaceHolder (view class) which the MediaPlayer can render the video on
    88. 88. 6. What’s next?
    89. 89. More Topics• Location (GPS) and Map• Bluetooth• USB host and accessory• Animation• OpenGL ES
    90. 90. Arduino & Bluetooth
    91. 91. Notepad Tutorial• Exercise 1- ListActivity and database http://developer.android.com/resources/tutorials/notepad/notepad-ex1.html• Exercise 2 - Invoke another activity• Exercise 3 - application life cycle
    92. 92. Sample Code• Sample Codes http://developer.android.com/resources/samples/get.html• API Demo, Bluetooth Chat, News Reader, Accelerometer Play, Contact Manager, etc
    93. 93. User Interfaces• Supporting different screen sizes http://developer.android.com/guide/practices/screens_support.html• Common UI Patterns http://www.androidpatterns.com/
    94. 94. Change view on a set of data
    95. 95. Select multiple items
    96. 96. Dashboard
    97. 97. Important Resources• http://developer.android.com• http://stackoverflow.com/• http://www.google.com/

    ×