Upgrade to Pro — share decks privately, control downloads, hide ads and more …

From JavaEE to Android

From JavaEE to Android

Android for beginners. Presented at JUG Kyiv in 2014.

More Android stuff:
https://medium.com/@sergii
https://twitter.com/sergiizhuk

Sergii Zhuk

July 24, 2014
Tweet

More Decks by Sergii Zhuk

Other Decks in Programming

Transcript

  1. 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
  2. Agenda • History and the 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. 4

  5. How to start • JDK • Android SDK • Java

    IDE + Android plugin • Gradle build system (optional) 6
  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
  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
  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
  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
  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
  11. Multiple screens support (2) • Alternative drawable resources for different

    screen densities • Vector xml-defined graphics – put to default drawable folder 12
  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
  13. 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); }
  14. 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); }
  15. 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
  16. 19 Common layouts – adapter-based List View Grid View Displays

    a scrolling single column list Displays a scrolling grid of columns and rows
  17. 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
  18. 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
  19. 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
  20. 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 26 http://www.grokkingandroid.com/sqlite-in-android/
  21. 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
  22. 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 28 http://www.grokkingandroid.com/sqlite-in-android/
  23. 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
  24. 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
  25. 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 ); }
  26. 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
  27. 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
  28. 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
  29. Use Case: integration with social networks • REST API with

    OAuth authorization • Vendor-provided libraries • Third-party libraries 35
  30. Run your app • Android SDK Emulator • VirtualBox ones

    like Genymotion • Real device – must have! 37
  31. How to build your app • In IDE  •

    Old-fashioned build tools: Ant, Maven • Gradle 38
  32. 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
  33. 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 } }
  34. 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
  35. 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 43 http://martinfowler.com/articles/continuousIntegration.html
  36. Where to publish your app • Google Play Store •

    Samsung Apps • Amazon Appstore for Android • Smaller distribution networks 45
  37. 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