Android Programming 101
for NTU Workshop 2013
About Me

Name
Work at
No. of apps
Find me at

Junda Ong
Hoiio
20+
just2me.com, samwize.com
@samwize, G+
Hoiio API
Hoiio Business Communication
Hoiio Phone
My Hobby Projects
txeet
SG 4D

BAD Example of Porting
About You ?
Today’s Programme
8am - 10am

Setting Up Android Studio

10am - 12pm

Introduction to Android Programming

12pm - 1pm

Lun...
Objectives

Understand Android development process
Master Android Studio
Kickstart basic Android programming
Pre-requisite: Java Programming

Java Programming Guide:
http://mobile.tutsplus.com/tutorials/android/java-tutorial/
Introduction to Android
The Android OS

• Linux Kernel
• Write in Java code
• Dalvik Virtual Machine
• Application Framework
Android Architecture
Platform Versions
Development Process
Design

Develop

Distribute
Learn how to Design
Understanding Design

• Principles/Guidelines
• UI Components
• Common Patterns
Design Principles

• Simple
• Looks the same, act the same
• Customizable
• Icon style
• Don’t mimic iPhone UI
UI Components

• Buttons
• Text Fields
• Dialogs
• Spinners
• Action Bar
Button
Text Fields
Dialogs
Alerts
Spinner
Action Bar
Common Patterns
Change view on a set of data
Select multiple items
Dashboard
Devices & Resolutions
dpi = dots per inch

dp = density independent pixels

for graphics

(1dp might be 1 pixel or 2 pixels, depending on the dp...
App Icon
48x48 dp

48x48 px

72x72 px

96x96 px

144x144 px
Learn how to Code
AndroidManifest.xml
4 Main Components

1. Activity
2. Service
3. Content Provider
4. Broadcast Receiver
Activity

• Activity = Screen
• An app is made up of 1 or more activities
• Stack of activities/screens
• Activity lifecyc...
Activity

• App-X can activate App-Y component
• Intent
• App-X can access App-Y shared data
• Content Resolver
HelloWorldActivity

Activity 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

•

Activity must be declared in AndroidManifest.xml
<manifest ... >
  <application ... >
      <activity android...
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.

• You can ac...
BroadcastReceiver

• Responds to system-wide broadcast

announcements such as incoming phone
call, SMS sent, picture captu...
User Interfaces

Slides on http://www.slideshare.net/samwize
View Hierarchy

1. View - Android UI component, view or widget
2. ViewGroup - Layout or container view
View

• UI components can be found in
android.widget package

•

Basic UI:

•
•
•
•
•
•

TextView
Button
TextField
Progres...
ViewGroup
(aka layout manager)

A simple LinearLayout
ViewGroup

TableLayout
ViewGroup

RelativeLayout
User Interfaces

• 3 ways to construct UI
1. Drag-and-drop interface builder
2. XML
3. Code
The way of XML
/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.and...
The way of XML
/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.and...
The way of Code
package com.just2us.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.wi...
Preferences

• The easiest way to store information
• NOT only store preferences/settings, but
also arbitrary key-value pa...
Preferences
public class Calc extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";
    @Override
...
Network

• Connect to web services over HTTP
• Permission needed in Manifest
<uses-permission android:name="android.permis...
Network - GET
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.myserver.com/script1....
Network - POST

HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("http://www.myserver.com/logi...
Multimedia

• Camera
• Playback audio and video
Multimedia - Camera

• 2 ways to capture photo
• Using capture intent
• Using Camera class directly
Multimedia - Camera

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private Uri fileUri;
@Override
pu...
Multimedia - Camera
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
private Uri fileUri;
@Override
pub...
Multimedia - Camera
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private static final int CAPTURE_V...
Multimedia - MediaPlayer

• Play audio and video from:
• /res/raw/
• File system (internal or external)
• Stream over Inte...
Multimedia - MediaPlayer

MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
mediaPlayer.start();
...
1. Hello World [60 min]
Objectives

• Create new project
• Understand project structure
• Navigate in Android Studio
• Run & Debug
Demo!
Project Structure

Java Code
Project Structure

Resources
The steps in brief..

• Create new project
• Change App name
• Run
• View logs
• Debug
Refer to hand-out 1 notes
2. Stopwatch [60 min]
Objectives

• Create widgets in design mode
• Edit widgets in XML text mode
• Code how stopwatch works
Demo!
The steps in brief..

• Create 2 buttons
• Edit the names and id
• Code the stopwatch logic
Refer to hand-out 2 notes
3. Polish Stopwatch [60 min]
Objectives

• Create Responsive Layout
• Style the UI
• Enhance UX
Demo!
The steps in brief..

• Edit layout
• Add background image
• Custom font
• Button with background image
• Button with stat...
What’s Next?
Database

• Tabular data
• SQLite behind the scenes
• Extend SQLiteOpenHelper
Database
public class DictionaryOpenHelper extends SQLiteOpenHelper {
 
 
 
 
 
 

 
 
 
 
 
 

private
private
private
  ...
Database

• Call getWritableDatabase() or

getReadableDatabase() to get an
SQLiteDatabase object

• With SQLiteDatabase, c...
More Topics

• Location (GPS) and Map
• Bluetooth
• USB host and accessory
• Animation
• OpenGL ES
• Push Messaging (GCM)
Arduino & Bluetooth
Important Resources

• http://developer.android.com
• http://stackoverflow.com/
• http://www.google.com/
Android Workshop 2013
Android Workshop 2013
Android Workshop 2013
Android Workshop 2013
Android Workshop 2013
Android Workshop 2013
Android Workshop 2013
Android Workshop 2013
Android Workshop 2013
Android Workshop 2013
Upcoming SlideShare
Loading in …5
×

Android Workshop 2013

1,400
-1

Published on

A 1 day NTU workshop for kickstarting Android development. Includes using the newest & better IDE - Android Studio - and a thorough process from developing you idea > mockup > coding > polishing > distributing.

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,400
On Slideshare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
211
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Android Workshop 2013

  1. 1. Android Programming 101 for NTU Workshop 2013
  2. 2. About Me Name Work at No. of apps Find me at Junda Ong Hoiio 20+ just2me.com, samwize.com @samwize, G+
  3. 3. Hoiio API
  4. 4. Hoiio Business Communication
  5. 5. Hoiio Phone
  6. 6. My Hobby Projects
  7. 7. txeet
  8. 8. SG 4D BAD Example of Porting
  9. 9. About You ?
  10. 10. Today’s Programme 8am - 10am Setting Up Android Studio 10am - 12pm Introduction to Android Programming 12pm - 1pm Lunch 1pm - 5pm 3 x hands-on (each 1 hr)
  11. 11. Objectives Understand Android development process Master Android Studio Kickstart basic Android programming
  12. 12. Pre-requisite: Java Programming Java Programming Guide: http://mobile.tutsplus.com/tutorials/android/java-tutorial/
  13. 13. Introduction to Android
  14. 14. The Android OS • Linux Kernel • Write in Java code • Dalvik Virtual Machine • Application Framework
  15. 15. Android Architecture
  16. 16. Platform Versions
  17. 17. Development Process Design Develop Distribute
  18. 18. Learn how to Design
  19. 19. Understanding Design • Principles/Guidelines • UI Components • Common Patterns
  20. 20. Design Principles • Simple • Looks the same, act the same • Customizable • Icon style • Don’t mimic iPhone UI
  21. 21. UI Components • Buttons • Text Fields • Dialogs • Spinners • Action Bar
  22. 22. Button
  23. 23. Text Fields
  24. 24. Dialogs
  25. 25. Alerts
  26. 26. Spinner
  27. 27. Action Bar
  28. 28. Common Patterns
  29. 29. Change view on a set of data
  30. 30. Select multiple items
  31. 31. Dashboard
  32. 32. Devices & Resolutions
  33. 33. dpi = dots per inch dp = density independent pixels for graphics (1dp might be 1 pixel or 2 pixels, depending on the dpi) sp = scale independent pixels for fonts
  34. 34. App Icon 48x48 dp 48x48 px 72x72 px 96x96 px 144x144 px
  35. 35. Learn how to Code
  36. 36. AndroidManifest.xml
  37. 37. 4 Main Components 1. Activity 2. Service 3. Content Provider 4. Broadcast Receiver
  38. 38. Activity • Activity = Screen • An app is made up of 1 or more activities • Stack of activities/screens • Activity lifecycle
  39. 39. Activity • App-X can activate App-Y component • Intent • App-X can access App-Y shared data • Content Resolver
  40. 40. HelloWorldActivity Activity 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); Launch a system Activity Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); startActivity(intent);
  42. 42. Activity • Activity must be declared in AndroidManifest.xml <manifest ... >   <application ... >       <activity android:name=".HelloWorldActivity" />       ...   </application ... >   ... </manifest > .HelloWorldActivity is shorthand for com.just2us.helloworld.HelloWorldActivity
  43. 43. 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
  44. 44. ContentProvider • A way to share data across applications, including apps such as phonebook, calendar, etc. • You can access the phonebook data using a ContentResolver • Have query, insert, delete methods (SQLite) ContentResolver cr = getContentResolver(); cr.query(“content://android.provider.Contacts.Phones.CONTACT_URI”, projection, selection, selectionArg, sortOrder)
  45. 45. BroadcastReceiver • Responds to system-wide broadcast announcements such as incoming phone call, SMS sent, picture captured, etc
  46. 46. User Interfaces Slides on http://www.slideshare.net/samwize
  47. 47. View Hierarchy 1. View - Android UI component, view or widget 2. ViewGroup - Layout or container view
  48. 48. View • UI components can be found in android.widget package • Basic UI: • • • • • • TextView Button TextField Progress bar List etc..
  49. 49. ViewGroup (aka layout manager) A simple LinearLayout
  50. 50. ViewGroup TableLayout
  51. 51. ViewGroup RelativeLayout
  52. 52. User Interfaces • 3 ways to construct UI 1. Drag-and-drop interface builder 2. XML 3. Code
  53. 53. 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” Equivalently.. android:text="Hello world too!"
  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> @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } setContentView() inflate main.xml and set the views
  55. 55. The way of Code package 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 Similarly to the way of XML, setContentView()
  56. 56. Preferences • The easiest way to store information • NOT only store preferences/settings, but also arbitrary key-value pairs • SharedPreference class • getBoolean, setBoolean, etc..
  57. 57. Preferences public 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();     } }
  58. 58. 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
  59. 59. Network - GET HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet("http://www.myserver.com/script1.php"); // Execute HTTP GET request and get response HttpResponse 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 ...
  60. 60. Network - POST HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost("http://www.myserver.com/login_script.php"); // Add your data List<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 Request HttpResponse response = httpclient.execute(request);        
  61. 61. Multimedia • Camera • Playback audio and video
  62. 62. Multimedia - Camera • 2 ways to capture photo • Using capture intent • Using Camera class directly
  63. 63. Multimedia - Camera private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100; private Uri fileUri; @Override public 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
  64. 64. Multimedia - Camera private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200; private Uri fileUri; @Override public 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
  65. 65. Multimedia - Camera private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100; private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200; @Override protected 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
  66. 66. Multimedia - MediaPlayer • Play audio and video from: • /res/raw/ • File system (internal or external) • Stream over Internet • MediaPlayer class
  67. 67. Multimedia - MediaPlayer MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1); mediaPlayer.start(); ... mediaPlayer.stop(); Playing /res/raw/sound_file_1.mp3
  68. 68. 1. Hello World [60 min]
  69. 69. Objectives • Create new project • Understand project structure • Navigate in Android Studio • Run & Debug
  70. 70. Demo!
  71. 71. Project Structure Java Code
  72. 72. Project Structure Resources
  73. 73. The steps in brief.. • Create new project • Change App name • Run • View logs • Debug Refer to hand-out 1 notes
  74. 74. 2. Stopwatch [60 min]
  75. 75. Objectives • Create widgets in design mode • Edit widgets in XML text mode • Code how stopwatch works
  76. 76. Demo!
  77. 77. The steps in brief.. • Create 2 buttons • Edit the names and id • Code the stopwatch logic Refer to hand-out 2 notes
  78. 78. 3. Polish Stopwatch [60 min]
  79. 79. Objectives • Create Responsive Layout • Style the UI • Enhance UX
  80. 80. Demo!
  81. 81. The steps in brief.. • Edit layout • Add background image • Custom font • Button with background image • Button with states Refer to hand-out 3 notes
  82. 82. What’s Next?
  83. 83. Database • Tabular data • SQLite behind the scenes • Extend SQLiteOpenHelper
  84. 84. Database public class DictionaryOpenHelper extends SQLiteOpenHelper {                         private private private                         static final int DATABASE_VERSION = 2; static final String DICTIONARY_TABLE_NAME = "dictionary"; 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); }
  85. 85. Database • Call getWritableDatabase() or getReadableDatabase() to get an SQLiteDatabase object • With SQLiteDatabase, call query() to execute SQL queries
  86. 86. More Topics • Location (GPS) and Map • Bluetooth • USB host and accessory • Animation • OpenGL ES • Push Messaging (GCM)
  87. 87. Arduino & Bluetooth
  88. 88. Important Resources • http://developer.android.com • http://stackoverflow.com/ • http://www.google.com/
  1. A particular slide catching your eye?

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

×