From JavaEE to Android: Way in one click? Sergii Zhuk Android/Java Developer at DAXX BV Kyiv, 2014-07-24 1 Android for beginners from the former JavaEE developer
Agenda • History and the market share • How to start • Application components • UI development • Working with a database • Build tools and continuous integration • Publishing 2
Android: the history • Founded in Palo Alto, CA in 2003 • Acquired by Google in 2005 • First commercial smartphone: HTC Dream, Oct 2008 • Driven by Linux Kernel • Open Source Project 3
4
Android market share (2) https://developer.android.com/about/dashboards/index.html 5
How to start • JDK • Android SDK • Java IDE + Android plugin • Gradle build system (optional) 6
Typical project structure src/ Source code files res/ Application resources - drawable files, layout files, string values bin/ Output directory of the build gen/ Java files generated by Android Developer Tools like res codes assets/ Raw asset files. You can navigate this directory in the same way as a typical file system, the original filename is preserved libs/ Libraries AndroidManifest.xml The control file that describes the nature of the application and each of its components 7
The Manifest File Your app must declare all its components in AndroidManifest.xml file. This file contains: • user permissions the app requires (Internet access, local storage, …) • the minimum API Level required by the app • hardware and software features used (camera, bluetooth, …) • libraries the app needs to be linked (Google maps) • and more… 8
Manifest file example <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.sergez.splayer" android:versionCode="37" android:versionName="2.1"> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:debuggable="false" > <activity android:name=".activity.SimplePlayerActivity" android:label="@string/app_name“ android:theme="@style/Theme.Sherlock"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <service android:name=".service.SimplePlayerService" android:enabled="true"/> </application> </manifest> 9
Application Resources • Resources are separate from the source code • For every resource a unique integer ID will be generated, which you can use as reference from code • Ability to provide alternative resources for different device configurations 10
Multiple screens support (1) 11 • Density-independent pixel (dp) - A virtual pixel unit to express layout dimensions or position in a density-independent way. • px = dp * (dpi / 160) - for 160dpi screen • “wrap_content” and “match_parent” flexible sizes
Multiple screens support (2) • Alternative drawable resources for different screen densities • Vector xml-defined graphics – put to default drawable folder 12
Multiple screens support (3) Low density (120), ldpi Medium density (160), mdpi High density (240), hdpi Extra high density (320), xhdpi Small screen QVGA (240x320) 480x640 Normal screen WQVGA400 (240x400) WQVGA432 (240x432) HVGA (320x480) WVGA800 (480x800) WVGA854 (480x854) 600x1024 640x960 Large screen WVGA800 (480x800) WVGA854 (480x854) WVGA800 (480x800) WVGA854 (480x854) 600x1024 Extra Large screen 1024x600 WXGA (1280x800) 1024x768 1280x768 1536x1152 1920x1152 1920x1200 2048x1536 2560x1536 2560x1600 13 http://developer.android.com/guide/practices/screens_support.html
Application Resources example 14
Main UI components Source: http://www.itcsolutions.eu/2011/08/27/android-tutorial-4-procedural-vs-declarative-design-of-user-interfaces/ 15
16 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp"> <TextView android:text="@string/hello_world" android:layout_centerInParent="true" android:textSize="20sp" android:textColor="#FF444444" android:textStyle="bold|italic" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> Procedural vs. Declarative Design of UI (1) /java/org/sergez/jugdemo1/MainActivity.java /res/layout/activity_main.xml @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }
Procedural vs. Declarative Design of UI (2) 17 /java/org/sergez/jugdemo1/MainActivity.java @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); RelativeLayout mainLayout = new RelativeLayout(this); RelativeLayout.LayoutParams mainLayoutParams = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); mainLayout.setLayoutParams(mainLayoutParams); TextView textInfo = new TextView(this); textInfo.setText("Hello World!"); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); textLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); textInfo.setLayoutParams(textLayoutParams); textInfo.setTextSize(20); textInfo.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC); textInfo.setTextColor(Color.DKGRAY); mainLayout.addView(textInfo); setContentView(mainLayout); }
Common layouts 18 Organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen. Enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent). Linear Layout Relative Layout
19 Common layouts – adapter-based List View Grid View Displays a scrolling single column list Displays a scrolling grid of columns and rows
App Components Each component is a different point through which the system can enter your app: • Activities • Services • Content providers • Broadcast receivers http://developer.android.com/guide/components/fundamentals.html 20
Activity • Provides a screen with which users can interact in order to do something • One activity in an application is specified as the "main" activity - launching the application • When an activity is stopped because a new activity starts, it is notified of this change in state through lifecycle callback methods 21
Activity lifecycle 22
Service • Perform long-running operations in the background and does not provide a user interface • Runs in the main thread of its hosting process— the service does not create its own thread and does not run in a separate process (unless you specify otherwise). • Should be defined in AndroidManifest.xml 23
Service workflow 24
Save application data • SharedPreferences (key/value pairs) • Files (internal/external storage) • SQLite database 25
SQLite database • Serverless • Stores data in one database file • Has no fixed column length • Uses cross-platform database files • Is used not only by Android but also by Apple’s iOS and Blackberry’s system 26http://www.grokkingandroid.com/sqlite-in-android/
SQLite database • Every app developer can rely on SQLite being present on an Android system • Android doesn’t use JDBC • You can’t use another database in Android • Not encrypted by default, can be accessed on rooted devices: /data/data/<package-name>/databases 27
SQLite for Android: data types Type Meaning INTEGER Any number which is not a floating point number REAL Floating-point numbers (8-Byte IEEE 754 – i.e. double precision) TEXT Any String and also single characters (UTF-8, UTF-16BE or UTF-16LE) BLOB A binary blob of data 28http://www.grokkingandroid.com/sqlite-in-android/
Content provider (1) • Presents data to external applications as one or more tables that are similar to the tables found in a relational database • Android itself includes content providers for data such as audio, video, images, and Contacts • Thread safe, asynchronous 29
Content provider (2) • An application accesses the data from a content provider with a ContentResolver client object which provides the basic CRUD • Should be declared in AndroidManifest.xml 30
Content provider (3) 31 public static int markStatus(Context context, String localId, Status status) { ContentValues values = new ContentValues(); String where = DBHelper.COL_UUID + " = ?"; String[] selectionArgs = new String[]{ String.valueOf(localId) }; values.put(DBHelper.COL_STATUS, status.ordinal()); return context.getContentResolver().update( MyContentProvider.CONTENT_URI_MYRESOURCE, values, where, selectionArgs ); }
Broadcast receiver • Allows to register for system or application events • Operates with Intent which is a lightweight messaging object • Normal broadcast: asynchronous - all receivers of the broadcast are run in an undefined order, often at the same time • Ordered broadcast: delivered to one receiver at a time, order can be controlled 32
System broadcasts example Event Description Intent.ACTION_BOOT_COMPLETED Boot completed. Intent.ACTION_POWER_CONNECTED Power got connected to the device. Intent.ACTION_POWER_DISCONNECTED Power got disconnected from the device. Intent.ACTION_BATTERY_LOW Triggered on low battery. Typically used to reduce activities in your app which consume power. Intent.ACTION_PHONE_STATE_CHANGED The call state (cellular) on the device has changed 33
Use Case: Interaction with backend • Synchronous HTTP request in the separate thread - OR use external library (Retrofit, Volley, Enroscar) • Parse result (for json - GSON is de-facto standard) • Post result to the UI 34
Use Case: integration with social networks • REST API with OAuth authorization • Vendor-provided libraries • Third-party libraries 35
Use Case: integration with social networks - library 36
Run your app • Android SDK Emulator • VirtualBox ones like Genymotion • Real device – must have! 37
How to build your app • In IDE  • Old-fashioned build tools: Ant, Maven • Gradle 38
Gradle • Good IDE integration and single build system • Built-in dependency management through Maven and/or Ivy. • Built-in signing for applications • Backward compatibility may not work properly sometimes 39
Gradle build script example 40 buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.9.+' } } apply plugin: 'android' repositories { mavenCentral() } dependencies { compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar' compile 'com.android.support:support-v4:18.0.+' } android { compileSdkVersion 19 buildToolsVersion "19.1.0" lintOptions { abortOnError false } }
Demo project 41
Testing • Manual  • Unit testing – JUnit 3 out of the box • Robotium: blackbox UI testing in emulator • Robolectric: tests are to be run outside the emulator – in a JVM, not in the Dalvik VM 42
Continuous integration in general • Maintain a code repository • Automate the build • Make the build self-testing • Make it easy to get the latest deliverables • Everyone can see the results of the latest build • And more 43http://martinfowler.com/articles/continuousIntegration.html
Continuous integration: mainstream for Android • Jenkins CI • Travis CI • CIsimple 44
Where to publish your app • Google Play Store • Samsung Apps • Amazon Appstore for Android • Smaller distribution networks 45
Publish on Google Play Store • Live demo 46
What to read & try • https://developer.android.com • http://android-developers.blogspot.com/ • Dig in sources • CommonsGuy blog & book • Coursera courses: Programming Cloud Services for Android Handheld Systems and others 47
Thanks! Contact me: sergey.public@gmail.com http://ua.linkedin.com/in/sergiizhuk http://fb.com/sergii.zhuk 48

From JavaEE to Android: Way in one click?

  • 1.
    From JavaEE toAndroid: Way in one click? Sergii Zhuk Android/Java Developer at DAXX BV Kyiv, 2014-07-24 1 Android for beginners from the former JavaEE developer
  • 2.
    Agenda • History andthe market share • How to start • Application components • UI development • Working with a database • Build tools and continuous integration • Publishing 2
  • 3.
    Android: the history •Founded in Palo Alto, CA in 2003 • Acquired by Google in 2005 • First commercial smartphone: HTC Dream, Oct 2008 • Driven by Linux Kernel • Open Source Project 3
  • 4.
  • 5.
    Android market share(2) https://developer.android.com/about/dashboards/index.html 5
  • 6.
    How to start •JDK • Android SDK • Java IDE + Android plugin • Gradle build system (optional) 6
  • 7.
    Typical project structure src/Source code files res/ Application resources - drawable files, layout files, string values bin/ Output directory of the build gen/ Java files generated by Android Developer Tools like res codes assets/ Raw asset files. You can navigate this directory in the same way as a typical file system, the original filename is preserved libs/ Libraries AndroidManifest.xml The control file that describes the nature of the application and each of its components 7
  • 8.
    The Manifest File Yourapp must declare all its components in AndroidManifest.xml file. This file contains: • user permissions the app requires (Internet access, local storage, …) • the minimum API Level required by the app • hardware and software features used (camera, bluetooth, …) • libraries the app needs to be linked (Google maps) • and more… 8
  • 9.
    Manifest file example <?xmlversion="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.sergez.splayer" android:versionCode="37" android:versionName="2.1"> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:debuggable="false" > <activity android:name=".activity.SimplePlayerActivity" android:label="@string/app_name“ android:theme="@style/Theme.Sherlock"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <service android:name=".service.SimplePlayerService" android:enabled="true"/> </application> </manifest> 9
  • 10.
    Application Resources • Resourcesare separate from the source code • For every resource a unique integer ID will be generated, which you can use as reference from code • Ability to provide alternative resources for different device configurations 10
  • 11.
    Multiple screens support(1) 11 • Density-independent pixel (dp) - A virtual pixel unit to express layout dimensions or position in a density-independent way. • px = dp * (dpi / 160) - for 160dpi screen • “wrap_content” and “match_parent” flexible sizes
  • 12.
    Multiple screens support(2) • Alternative drawable resources for different screen densities • Vector xml-defined graphics – put to default drawable folder 12
  • 13.
    Multiple screens support(3) Low density (120), ldpi Medium density (160), mdpi High density (240), hdpi Extra high density (320), xhdpi Small screen QVGA (240x320) 480x640 Normal screen WQVGA400 (240x400) WQVGA432 (240x432) HVGA (320x480) WVGA800 (480x800) WVGA854 (480x854) 600x1024 640x960 Large screen WVGA800 (480x800) WVGA854 (480x854) WVGA800 (480x800) WVGA854 (480x854) 600x1024 Extra Large screen 1024x600 WXGA (1280x800) 1024x768 1280x768 1536x1152 1920x1152 1920x1200 2048x1536 2560x1536 2560x1600 13 http://developer.android.com/guide/practices/screens_support.html
  • 14.
  • 15.
    Main UI components Source:http://www.itcsolutions.eu/2011/08/27/android-tutorial-4-procedural-vs-declarative-design-of-user-interfaces/ 15
  • 16.
  • 17.
    Procedural vs. DeclarativeDesign of UI (2) 17 /java/org/sergez/jugdemo1/MainActivity.java @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); RelativeLayout mainLayout = new RelativeLayout(this); RelativeLayout.LayoutParams mainLayoutParams = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); mainLayout.setLayoutParams(mainLayoutParams); TextView textInfo = new TextView(this); textInfo.setText("Hello World!"); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); textLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); textInfo.setLayoutParams(textLayoutParams); textInfo.setTextSize(20); textInfo.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC); textInfo.setTextColor(Color.DKGRAY); mainLayout.addView(textInfo); setContentView(mainLayout); }
  • 18.
    Common layouts 18 Organizes itschildren into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen. Enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent). Linear Layout Relative Layout
  • 19.
    19 Common layouts –adapter-based List View Grid View Displays a scrolling single column list Displays a scrolling grid of columns and rows
  • 20.
    App Components Each componentis a different point through which the system can enter your app: • Activities • Services • Content providers • Broadcast receivers http://developer.android.com/guide/components/fundamentals.html 20
  • 21.
    Activity • Provides ascreen with which users can interact in order to do something • One activity in an application is specified as the "main" activity - launching the application • When an activity is stopped because a new activity starts, it is notified of this change in state through lifecycle callback methods 21
  • 22.
  • 23.
    Service • Perform long-runningoperations in the background and does not provide a user interface • Runs in the main thread of its hosting process— the service does not create its own thread and does not run in a separate process (unless you specify otherwise). • Should be defined in AndroidManifest.xml 23
  • 24.
  • 25.
    Save application data •SharedPreferences (key/value pairs) • Files (internal/external storage) • SQLite database 25
  • 26.
    SQLite database • Serverless •Stores data in one database file • Has no fixed column length • Uses cross-platform database files • Is used not only by Android but also by Apple’s iOS and Blackberry’s system 26http://www.grokkingandroid.com/sqlite-in-android/
  • 27.
    SQLite database • Everyapp developer can rely on SQLite being present on an Android system • Android doesn’t use JDBC • You can’t use another database in Android • Not encrypted by default, can be accessed on rooted devices: /data/data/<package-name>/databases 27
  • 28.
    SQLite for Android:data types Type Meaning INTEGER Any number which is not a floating point number REAL Floating-point numbers (8-Byte IEEE 754 – i.e. double precision) TEXT Any String and also single characters (UTF-8, UTF-16BE or UTF-16LE) BLOB A binary blob of data 28http://www.grokkingandroid.com/sqlite-in-android/
  • 29.
    Content provider (1) •Presents data to external applications as one or more tables that are similar to the tables found in a relational database • Android itself includes content providers for data such as audio, video, images, and Contacts • Thread safe, asynchronous 29
  • 30.
    Content provider (2) •An application accesses the data from a content provider with a ContentResolver client object which provides the basic CRUD • Should be declared in AndroidManifest.xml 30
  • 31.
    Content provider (3) 31 publicstatic int markStatus(Context context, String localId, Status status) { ContentValues values = new ContentValues(); String where = DBHelper.COL_UUID + " = ?"; String[] selectionArgs = new String[]{ String.valueOf(localId) }; values.put(DBHelper.COL_STATUS, status.ordinal()); return context.getContentResolver().update( MyContentProvider.CONTENT_URI_MYRESOURCE, values, where, selectionArgs ); }
  • 32.
    Broadcast receiver • Allowsto register for system or application events • Operates with Intent which is a lightweight messaging object • Normal broadcast: asynchronous - all receivers of the broadcast are run in an undefined order, often at the same time • Ordered broadcast: delivered to one receiver at a time, order can be controlled 32
  • 33.
    System broadcasts example EventDescription Intent.ACTION_BOOT_COMPLETED Boot completed. Intent.ACTION_POWER_CONNECTED Power got connected to the device. Intent.ACTION_POWER_DISCONNECTED Power got disconnected from the device. Intent.ACTION_BATTERY_LOW Triggered on low battery. Typically used to reduce activities in your app which consume power. Intent.ACTION_PHONE_STATE_CHANGED The call state (cellular) on the device has changed 33
  • 34.
    Use Case: Interactionwith backend • Synchronous HTTP request in the separate thread - OR use external library (Retrofit, Volley, Enroscar) • Parse result (for json - GSON is de-facto standard) • Post result to the UI 34
  • 35.
    Use Case: integrationwith social networks • REST API with OAuth authorization • Vendor-provided libraries • Third-party libraries 35
  • 36.
    Use Case: integrationwith social networks - library 36
  • 37.
    Run your app •Android SDK Emulator • VirtualBox ones like Genymotion • Real device – must have! 37
  • 38.
    How to buildyour app • In IDE  • Old-fashioned build tools: Ant, Maven • Gradle 38
  • 39.
    Gradle • Good IDEintegration and single build system • Built-in dependency management through Maven and/or Ivy. • Built-in signing for applications • Backward compatibility may not work properly sometimes 39
  • 40.
    Gradle build scriptexample 40 buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.9.+' } } apply plugin: 'android' repositories { mavenCentral() } dependencies { compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar' compile 'com.android.support:support-v4:18.0.+' } android { compileSdkVersion 19 buildToolsVersion "19.1.0" lintOptions { abortOnError false } }
  • 41.
  • 42.
    Testing • Manual  •Unit testing – JUnit 3 out of the box • Robotium: blackbox UI testing in emulator • Robolectric: tests are to be run outside the emulator – in a JVM, not in the Dalvik VM 42
  • 43.
    Continuous integration ingeneral • Maintain a code repository • Automate the build • Make the build self-testing • Make it easy to get the latest deliverables • Everyone can see the results of the latest build • And more 43http://martinfowler.com/articles/continuousIntegration.html
  • 44.
    Continuous integration: mainstream forAndroid • Jenkins CI • Travis CI • CIsimple 44
  • 45.
    Where to publishyour app • Google Play Store • Samsung Apps • Amazon Appstore for Android • Smaller distribution networks 45
  • 46.
    Publish on GooglePlay Store • Live demo 46
  • 47.
    What to read& try • https://developer.android.com • http://android-developers.blogspot.com/ • Dig in sources • CommonsGuy blog & book • Coursera courses: Programming Cloud Services for Android Handheld Systems and others 47
  • 48.