CuuDuongThanCong.com Pro Android Wearables Building Apps for Smartwatches Wallace Jackson CuuDuongThanCong.com Pro Android Wearables: Building Apps for Smartwatches Copyright © 2015 by Wallace Jackson This work is subject to copyright All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer Permissions for use may be obtained through RightsLink at the Copyright Clearance Center Violations are liable to prosecution under the respective Copyright Law ISBN-13 (pbk): 978-1-4302-6550-4 ISBN-13 (electronic): 978-1-4302-6551-1 Trademarked names, logos, and images may appear in this book Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made The publisher makes no warranty, express or implied, with respect to the material contained herein Managing Director: Welmoed Spahr Lead Editor: Steve Anglin Technical Reviewer: Jeff Tang Editorial Board: Steve Anglin, Louise Corrigan, Jim DeWolf, Jonathan Gennick, Robert Hutchinson, Michelle Lowman, James Markham, Susan McDermott, Matthew Moodie, Jeffrey Pepper, Douglas CuuDuongThanCong.com Pundick, Ben Renow-Clarke, Gwenan Spearing, Steve Weiss Coordinating Editor: Mark Powers Copy Editor: Mary Bearden Compositor: SPi Global Indexer: SPi Global Artist: SPi Global Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc) SSBM Finance Inc is a Delaware corporation For information on translations, please e-mail rights@apress.com, or visit www.apress.com Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use eBook versions and licenses are also available for most titles For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales Any source code or other supplementary material referenced by the author in this text is available to readers at www.apress.com/9781430265504 For additional information about how to locate and download your book’s source code, go to www.apress.com/source-code/ Readers can also access source code at SpringerLink in the Supplementary Material section for each chapter CuuDuongThanCong.com The Pro Android Wearables book is dedicated to everyone in the open source community who is working diligently to make professional new media application development software and content development tools freely available to rich application developers to utilize to achieve our creative dreams and our financial goals Last, but not least, I dedicate this book to my father, Parker Jackson, my family, my life-long friends, and all my ranch neighbors, for their constant help, assistance, and those relaxing, late night BBQ parties CuuDuongThanCong.com Contents at a Glance About the Author About the Technical Reviewer Acknowledgments Introduction Chapter 1: Introduction to Android Wearables: Concepts, Types, and Material Design Chapter 2: Setting Up an Android Wearables Application Development Workstation Chapter 3: A Foundation for Android Wearables: New Wearable Features in Android Chapter 4: Exploring Android Studio: Getting Familiar with the IntelliJ IDEA Chapter 5: Android Virtual Devices: Setting Up Wearables Application Emulators Chapter 6: Introduction to Android Watch Faces Design: Considerations and Concepts Chapter 7: Program Watch Faces for Wear: Creating the Watch Face Code Foundation Chapter 8: A Watch Faces Timing Engine: Using TimeZone, Time, and BroadcastReceiver Chapter 9: Implement a WatchFaces Engine: Core WatchFaces API Methods CuuDuongThanCong.com Chapter 10: WatchFaces Vector Design: Using Vector Graphics for WatchFaces Chapter 11: WatchFaces Bitmap Design: Using Raster Graphics for WatchFaces Chapter 12: WatchFaces Digital Imaging: Developing Multiple Mode Assets Chapter 13: Watch Face Configuration Companion Activity: Google Mobile Services Chapter 14: Watch Face Configuration Companion Activity Utility and Wearable API Chapter 15: Wearables Application Testing: Using Hardware Devices in Android Studio Chapter 16: Wear API Deprecation: Updating Apps to Use New Classes or Methods Chapter 17: The Future of Android IoT APIs: Android TV, Glass, Auto, and Wear Index CuuDuongThanCong.com Contents About the Author About the Technical Reviewer Acknowledgments Introduction Chapter 1: Introduction to Android Wearables: Concepts, Types, and Material Design Wearable Technology Defined: What Is a Wearable? Wearable Application Development: What Types of Apps? Android Wearable Fun: Augmented Reality, Edutainment, and Gamification Mainstream Wearables: Smartwatches and Smartglasses Smartwatches: Round Watch Face vs Square Organic Light-emitting Diode Smartglasses: Glasses and Other Smartglasses Manufacturers Wearable Application Programming Interfaces Android Studio 1.0: Android Wear SDK Google Glass Development Kit: GDK for Android or Mirror True Android or Android Peripheral: Bluetooth Link Wearable Apps Design: Android Material Design The Android Material Design Themes: Light and Dark Android Material Design View Widgets: Lists and Cards Android Material Design Effects: Shadows and Animation Android Material Design Graphics Processing: Drawables What You Will Learn from This Book Summary Chapter 2: Setting Up an Android Wearables Application Development Workstation Work Process for Creating an Android Workstation CuuDuongThanCong.com Android Development Workstation: Hardware Foundation Android Development Workstation: Software Foundation Java 7: Installing the Foundation for Android Studio Android Studio 1.0: Download the Android IDEA Installing Android Studio: IntelliJ IDEA and Android SDK Professional Digital Imaging Software: GIMP 2.8.14 Professional Digital Video Editing: Lightworks 12 Professional 3D Modeling and Animation: Blender Professional Digital Audio Editing: Audacity 2.0.6 Professional UI Design Wireframing: Pencil Project 2.0.5 Professional Business Software Suite: OpenOffice Other Open Source and Affordable Media Software Summary Chapter 3: A Foundation for Android Wearables: New Wearable Features in Android Android’s Project Volta: Power Management Tools Android Process Scheduler: JobScheduler and JobInfo Android Battery Optimizer: The BatteryHistorian Tool Android’s Network Connection: NFC and Bluetooth Android Multiple Network Support: ConnectivityManager Android Low Energy Bluetooth: The Bluetooth LE API Android NFC Improvements: Near Field Communication Android Media: Adding Wow-Factor to Wearables Digital Video Playback: MediaController and MediaSession Digital Audio Playback: Enhanced AudioTrack Precision Real-Time 3D Rendering: OpenGL ES and Extension Pack WebKit Media: WebView, WebAudio, WebGL, and WebRTC Android MediaBrowser Class: Browsing Third-Party Media Android Camera API: UHD Image Processing Support Android Notifications: LockScreen and MetaData LockScreen Notifications: Privacy Safeguard Control APIs CuuDuongThanCong.com Notification MetaData: Intelligent Notification Classification More Android Operating System Enhancements The Recents Screen: Concurrent Document Support Data Storage: Directory Structure Selection Support Second Screen: Screen Capturing and Screen Sharing Summary Chapter 4: Exploring Android Studio: Getting Familiar with the IntelliJ IDEA Updating IntelliJ IDEA: Using the Update Info Dialog Exploring IntelliJ IDEA: Help, Tips, and Keymaps Configure Android Studio: Using the SDK Manager Run As Administrator: Installing Using Admin Privileges Learning the IntelliJ IDEA Basics: Projects and SDK IntelliJ Project Level: Developing Android Applications IntelliJ Features: SDK, Language Support, and Auto-Coding Creating an Android Wearable App: Using IntelliJ Summary Chapter 5: Android Virtual Devices: Setting Up Wearables Application Emulators Using the AVD Manager: Creating Wear Emulators Using Wear Emulators: Testing Your Wearable App Using IntelliJ Run: Running Wearable Apps in Round Wear Switching AVDs: Running Apps in Round Wear ARM AVD Switching AVDs: Running Apps in Square Wear ARM AVD Summary Chapter 6: Introduction to Android Watch Faces Design: Considerations and Concepts Watch Face Design: Considerations and Guidelines A Watch Faces UI: Seamless Blending of Art and Function CuuDuongThanCong.com L LayerDrawable Leanback library LevelDrawable Low-bit ambient mode lowBitAmbientModeFlag boolean option Low-bit level ambient mode dithering Posterize option transflective screen M Macros and documentation Masking Material Design android:statusBarColor attribute android:theme attribute AppTheme CardView class cardBackgroundColor attribute cardCornerRadius attribute cardElevation attribute card_view:cardElevation attribute CardView widget Drawable API AnimatedStateListDrawable class Palette class setTint() method VectorDrawable class modularity RecyclerView widget shadows and animation Activity animations elevation property motion curve PathInterpolator class shared element transitions StateListAnimator class Touch feedback animations statusBarColor Theme.Holo Theme.Material MediaBrowserService class MediaStreamAudioDestinationNode method MediaStreamAudioSourceNode method Message.setData() method Meta-data tag Multidex application CuuDuongThanCong.com Multimodal Bitmaps conditional if() structure ensureModeSupport() methods interactive mode Set Tick Marks Color Square AVD Logical OR structure Low-bit ambient mode N Near field communication (NFC) Network connection Bluetooth Low Energy ConnectivityManager class NetworkRequest.Builder NFC Networking hardware and software NinePatchDrawable noConnectedDeviceDialog() method AlertDialog AlertDialog.Builder XML markup NodeApi interface error drop-down fetchConfigDataMap() method fromDataItem() method getDataItem() method getLocalNode() method getLocalNodeResult() method nested interfaces onResult() method public methods setResultCallback() method Target Class Uri.Builder class Notifications LockScreen MetaData O Obfuscation code onActivityResult() method onAmbientModeChanged() method onApplyWindowInsets() method onAvailable() callback method onCaptureCompleted() onConnected() method CuuDuongThanCong.com empty method structure GMS PATH_WITH_FEATURE PendingResult public interface setResultCallback() method Uri.Builder class Uri class OnConnectionFailedListener interface onCreateEngine() method onCreate() method onCreate(SurfaceHolder surface) onDestroy() method onDraw() method onInterruptionFilterChanged(int interruptionFilter) method onLayoutStubListener() method onLayoutInflated() method onLocationChanged() method onMessageReceived() method blockingConnect() method conditional if structures getData() method Java code on() methods onPause() method onPeerDisconnected() method onPropertiesChanged() method onReceive(Context context, Intent intent) method onResult() method DataItemResult DataMap class DataMapItem Class fromDataItem() Method getDataItem() Method getDataMap() method onShowFileChooser() method onStart() method onStop() method onSurface() method onTimeTick() method onVisibilityChanged() method Operating system actions P, Q Pencil Performance factor PermissionRequest class Plyglot Portable Network Graphics (PNG) postInvalidate() method CuuDuongThanCong.com Power management tools BatteryHistorian Tool JobInfo JobScheduler smartwatch manufacturers Pro Android wearables ActivityManager.AppTask class concurrent activity screens data storage screen capture screen sharing Pro Android Wearables affordable 3D software packages Android Studio Overview page animation Apache OpenOffice 4.1.1 Audacity project audacity.sourceforge.net UI element objects creation DSL/4G connection EditShare Lightworks EULA GIMP 2.8.14 (see GIMP 2.8.14) hardware installation Accept License Agreement extracting installer progress dialog IntelliJ IDEA Java Setup Progress dialog Java SE 7u71 JRE programs and features SDK Windows x64 link new media asset development tools Pencil software 3D modeling terms and conditions ProGuard Prototyping tool PROVIDE_BACKGROUND ProWatchFaceCompanionConfigActivity AndroidManifest child tag Jump to Source option strings.xml file XML markup CONFIG_WATCH_FACE ACTION Java class creation CuuDuongThanCong.com androidTest folder Choose Destination Directory dialog extends keyword implement methods option implements keyword OnConnectionFailedListener interface KEY_COLOR constants LinearLayout container color_array layout_weight parameter layout_width parameter String Array object String Color constants Tick Marks UI layout design setUpAllPickers() method setUpColorPickerListener() method setUpColorPickerSelection() method setUpColorPickerListener() method AdapterView.OnItemSelectedListener() method findViewById() method getItemAtPosition() method onItemSelected() method putInt() method sendConfigUpdateMessage() method sendMessage() method setUpAllPickers() method toByteArray() method setUpColorPickerSelection() method findViewById() method getResources() method getStringArray() method getString() method ProWatchFaceConfigListenerService class ConnectionResult class implement methods option MessageEvent interface onMessageReceived() method blockingConnect() method conditional if structures getData() method Java code ProWatchFaceService Subclass ProWatchFaceUtility class color constants Color.parseColor() method key constants key-value data pairs Nexuas API ARM emulator AVD emulator CuuDuongThanCong.com compile statements CPU/ABI column Gradle configuration file package error Run command Virtual Device Configuration dialog overwriteKeysInConfigDataMap() method parseColor() method parseOptionColor() method ProWatchFaceCompanionConfigActivity (see ProWatchFaceCompanionConfigActivity) putConfigDataItem() method PutDataMapRequest class asPutDataRequest() method create() method getDataMap() method getUri() method putAll() method putConfigDataItem() method toLowerCase() method unique identifier ProWatchFaceUtility(){ } constructor See Java singleton Public abstract class Public constructor method putAll() method putByteArray() method putDataMap() method R Real-Time 3D Rendering AEP OpenGL ES 3.1 compute shader effects Enhanced Texture Mapping stencil texture mapping tag Tegra K1 microprocessor Real-time communications (RTC) Real-world hardware devices See Hardware devices Rebuilding project structure RecyclerView library registerNetworkCallback() method registerReceiver() method registerTimeZoneReceiver() method conditional if() structure context object unregisterReceiver() unregisterTimeZoneReceiver() method release() method CuuDuongThanCong.com remove() method requestNetwork() method ResourcesCompat class S Scalable Vector Graphics (SVG) Search and replace, IntelliJ code format sendEmptyMessageDelayed() method sendEmptyMessage() method setAlpha() method setAmbientPeekMode(int ambientPeekMode) method setAntiAlias() method setARGB() method setBackgroundVisibility(int backgroundVisibility) method setBurnInProtect() method setCardPeekMode(int peekMode) method setCategory() method setColor() helper method setColor() method setContentView() method setGregorianChange() method setHotwordIndicatorGravity(int hotwordIndicatorGravity) method setInterval() method set() methods setOnLayoutInflatedListener() method setPeekOpacityMode(int peekOpacityMode) method setResultCallback() method setShowSystemUiTime(boolean showSystemUiTime) method setShowUnreadCountIndicator(boolean show) method setStatusBarGravity(int statusBarGravity) method setStrokeCap() method setStrokeWidth() method setStyle() method setTimeInMillis() method onDraw() method setTimeZone() method setTimeZone() Method setToNow() method setVisibility() method setWatchFaceStyle() method build() method configuration methods and constants gravity object IntelliJ method helper dialog setBackgroundVisibility() method setHotwordIndicatorGravity ShapeDrawable show() method size() method Smartphone and smartwatch CuuDuongThanCong.com Android Debug Bridge (see Android Debug Bridge (ADB)) bluetooth debugging Sony SmartWatch wear API Software Development Kit (SDK) analog WatchFace service class Google Play Services gradle files Gradle sync issue project import project invalidate and restart Java/XML manager bad record MAC error configure panel downloading SDK updates progress dialog bar fetching URL progress bar google USB driver selection install dialog package internal numbering schema project re-creation ProWatchFaceService upgrade process wear component Solid-state disk (SSD) Sony SmartWatch Speech recognition technology startActivityForResult() method startActivity() method startAdvertising() method startScan() method StateDrawable super keyword SurfaceHolder object interface methods onCreate() method switch() statement System.currentTimeMillis() getter method System time currentTimeMillis() method hand movement invalidate() method isInAmbientMode() method isTimerEnabled() method java system class WATCH_FACE_UPDATE_RATE option T taskAffinity parameter CuuDuongThanCong.com Television Television apps application definition cardView library declaration file leanback library recyclerView library XML markup code Tessellation Shader Theme attributes This keyword 3D Modeling Time class Code Time processing Time-related classes and methods Java Time Utility classes overview SurfaceHolder object time, handler, and BroadcastReceiver WatchFaceStyle.Builder WATCH_FACE_UPDATE constant TimeUnit class Time update message creation TimeZone class timeZoneReceiver timeZoneReceiver object registerTimeZoneReceiver() method setTimeZone() Method toBundle() method toByteArray() method toString(), hashCode(), and writeToParcel() methods U, V Unique user ID (UID) Universal serial bus (USB) drivers administrator menu option browse option computer (Hardware) management dialog device manager entry download driver file explorer utility finding model number installation configuration dialogs manufacturer web site Samsung web site search option work process unregisterTimeZoneReceiver() method Update info dialog CuuDuongThanCong.com updateTimeHandler UPDATE_TIME_MESSAGE constant UPDATE_TIME_MESSAGE value updateTimer() method updateTimeZoneReceiver W WAKE_LOCK constant WAKE_LOCK function WatchFace Drawing Engine Canvas public class centerX and centerY values Current Time drawLine() method for loop structure Hour Hand rotation IntelliJ isInAmbientMode() Method Java statement Math.PI method Minute Hand Line Sine function WatchFace Painting Engine class Paint.FontMetricsInt nested class class Paint.FontMetrics nested class copycat createHourHand() method createMinuteHand() method createSecondHand() method createTickMarks() method enum Paint.Align nested class enum Paint.Cap nested class enum Paint.Join nested class enum Paint.Style nested class geometries Java class hierarchy code key components onCreate() method paint object declaration setAntiAlias() method setARGB() method setStrokeCap() method setStrokeWidth() method super.onCreate() superclass method TextPaint class URL WatchFaces Bitmap design createScaledBitmap() method digital image assets CuuDuongThanCong.com drawable objects android.graphics.drawable package getBitmap() method Java statement casts roundFlag Boolean XML definition file drawable objects creation getResources() method onApplyWindowInsets() method resources class Round AVD emulator Additional command line options bulletproof burn-in modes DDMS panel Disable boot animation Do not launch Activity option Edit Configurations dialog emulator-arm.exe error dialog handleMessage() method low-bit ambient mode RAM and Internal Storage Retry and Reset panes sendEmptyMessageDelayed() method Settings option setToNow() method Waiting for adb progress bar dialog testing first draw vs every draw onApplyWindowInsets() method onCreate() method onDraw() method round vs square WindowInsets class Watch Faces design activity_main.xml file ambient mode AnimationDrawable class Animation class Animation superclass hybrid animation transformations vector animation assumptions burn-in effect data assimilation data integration data visualization digital image format anti-aliasing concept blending mode CuuDuongThanCong.com color depth compression dithering Gaussian blur tool GIF Hexadecimal notation image aspect ratio image compositing JPEG masking pixels PNG resolution RGB color plane UHDTV screens WebP display screen hardware flexible design graphic file formats hybrid design interactive mode low-bit ambient mode OS-rendered UI elements CardView class launcher icon ListView objects OK Google phrase Peek Card Settings panel status indicators round_activity_main.xml file square_activity_main.xml file styles traditional analog clock vector graphics GradientDrawable class ShapeDrawable class SVG WatchFaceStyle.Builder builder methods setWatchFaceStyle() WatchFaceStyle class watchFaceTime WATCH_FACE_UPDATE constant Wearable class addApi() method DataItemResultCallback() method dataItemResult.getDataItem() method DataMapItem object getDataItem() method getStatus() method CuuDuongThanCong.com isSuccess() method onConfigDataMapFetched() method onResult() method fetchConfigDataMap() method error drop-down fromDataItem() method getDataItem() method getLocalNode() method getLocalNodeResult() method NodeApi interface onResult() method setResultCallback() method Target Class onConfigDataMapFetched() method putAll() method putConfigDataItem() method onResult() method overwriteKeysInConfigDataMap() method empty method fetchConfigDataMapCallback object GoogleApiClient object IntelliJ putDataItem() method setResultCallback() method Wearables AR Bluetooth edutainment gamification logical application verticals Material Design (see Material design) smartglasses smartwatches types Wearables application testing See also Hardware devices download and installation smartwatch Sony SmartWatch Wear API deprecation Android 5.2 calendar and getDrawable() getDrawable() and time IDE problems OS update Wear applications connection lifecycle getLastLocation() method Google Play Services onLocationChanged() method onPause() method onPeerDisconnected() method CuuDuongThanCong.com speech recognition technology Wear Emulators drop-down menu Host GPU option LogCat Run/Debug Configurations dialog Show chooser dialog option System Image dialog Target Device USB Device option using AVD Manager ARM and Intel processors ARM processor technology Hardware dialog Host GPU option IntelliJ Neptune Pine SmartWatch SmartWatch emulators Verify Configuration dialog Virtual Device Configuration dialog Virtual Devices dialog using IntelliJ Run adb progress bar AMD 8-core FX processor ARM version green Play (Run) icon HAXM intelhaxm-android.exe file MainActivity.java tab Paired screen power-saving mode ProAndroidWearable application round_activity_main.xml file Run/Debug dialog Run methods SmartWatch watch faces Wear start-up logo screen Verify Configuration dialog Wear SDK WebKit Media PermissionRequest class WebAudio API WebGL Support WebRTC Support Web Photo (WebP) format write() method X, Y, Z CuuDuongThanCong.com XML assets PNG images WatchFace Service declaration watch face wallpaper android resource directory menu sequence resource file version container tag XML definition structure CuuDuongThanCong.com .. .Pro Android Wearables Building Apps for Smartwatches Wallace Jackson CuuDuongThanCong.com Pro Android Wearables: Building Apps for Smartwatches Copyright © 2015 by Wallace Jackson This... Theme provides the new Android conforming style to use for your Android apps Because the Android Wear SDK is a part of Android Studio (Android plus IntelliJ), these new themes will apply to pro Android. ..