34,79 €
Android Wear Projects is your opportunity to step into the exciting new world of Android Wear app development. This book will help you to master the skills in Android Wear programming and give you a complete insight on wear app development.
You will create five different Android Wear apps just like the most popular Android Wear apps. You will create a To-do list, a city maps app, a Wear messenger, Wear fitness tracker and Watch face. While you create these apps you will learn to create custom notifications, receive voice inputs in notifications, add pages to notifications and stack notifications. You will see how to create custom wear app layouts, the custom UIs specially designed for Wear. You will learn to handle and manage data and syncing data with other devices, create interactive Watch faces and also ensure the safety and security of your Wear apps by testing and securing your apps before you deploy them on the app store.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 322
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: July 2017
Production reference: 1260717
ISBN 978-1-78712-322-9
www.packtpub.com
Author
Ashok Kumar S
Copy Editor
Akshata Lobo
Reviewers
Ravindra Kumar
Natarajan Raman
Project Coordinator
Ritika Manoj
Commissioning Editor
Amarabha Banerjee
Proofreader
Safis Editing
Acquisition Editor
Nigel Fernandes
Indexer
Mariammal Chettiyar
Content Development Editor
Mohammed Yusuf Imaratwale
Graphics
Jason Monteiro
Technical Editor
Rashil Shah
Production Coordinator
Shantanu Zagade
Ashok Kumar S is an Android developer residing in Bangalore, India. A gadget enthusiast, he thrives on innovating and exploring the latest gizmos in the tech space.
He has been developing Android applications for all Google-related technologies. He is a Google certified Udacity Nano degree holder.
A strong believer in spirituality, he heavily contributes to the open source community as a e-spiritual ritual to improve his e-karma. He regularly conducts workshops about Android application development in local engineering colleges and schools. He also organizes multiple tech events at his organization and is a regular attendee of all the conferences that happen on Android in the silicon valley of India.
He also has a YouTube channel, called AndroidABCD, where he discusses all aspects of Android development, including quick tutorials.
Ravindra Kumar is an Android developer and computer polyglot from Bengaluru, India. He is an Android and web speaker, startup geek, and open source junkie.
He works as an Android developer at Fueled. Previously, he worked with Cleartrip, as the lead developer of Cleartrip.com's Android app. He likes open source projects and is a huge fan of the fancy Android libraries out there. He contributes to bug reporting, fixing, and feedback, and has given talks at DroidCon, TiConf, and JSFOO.
He started as a web engineer who used to write lots of JavaScript, but after some time, looking for his real passion, he started his journey in mobile app development through Titanium. Later, he discovered the Android world. After getting some experience on such an awesome platform, he started a new adventure at a mobile company, where he led several projects for important Indian companies.
He has a strong interest in code quality, testing, and automation, and preferably all three together. Combining technical with soft skills, he also ventures into the realms of mentoring and article writing. He hates doing things manually, and hates to see src/test/java directories with empty example classes. He believes that by working with legacy code and improving it, he can make the world a better place. To his disappointment, the world does not seem to care all that much about his efforts.
He is a pretty normal person--a husband, father of one, and lover of cricket. You can follow @ravidsrk on Twitter or email him at [email protected].
Natarajan Raman has over 13 years of experience in software design and development with a good understanding and experience of the complete SDLC life cycle. Natarajan Raman is a Google/Udacity certified Nano degree holder on Android development. He was invited as a guest by Google to the I/O 2017, which was held in May in San Francisco, California.
Natarajan works for the Patterns design school and is also the managing trustee of Dream India, dreamindia.org, an NGO started by youngsters inspired by Dr. Kalam.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787123227. If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
Getting You Ready to Fly - Setting Up Your Development Environment
Android Wear design principles
Defining layouts
Creating lists
Exploring UI components for Wear devices
Showing confirmations
DelayedConfirmationView
Wear navigation and actions
Navigation drawer
Action drawer
Multifunction buttons
Setting up a development environment for Wear development
Installing Android Studio
Creating your first Android Wear application
Creating your first Wear project
Creating a Wear emulator
Working with actual Wear device
Debugging over Wi-Fi
Enable Bluetooth debugging
Summary
Let us Help Capture What is on Your Mind - WearRecyclerView and More
Getting started
Let's get started by creating a project
Lifecycle of an Android activity
Creating the packages
Creating the SharedPreference utility
Saving notes
Fetching all the saved notes from SharedPreference
Removing notes from SharedPreference
Building the User Interface
Creating an adapter for WearableRecyclerView
Adapter implementation
Working on activities and driving the project towards completion
Writing a method to create a note when clicking on Add a Note
Adding a method for updating the adapter
Adding the updateData method
Updating the data on the UI when the application restarts
Overriding onActivityResult for getting the delete reference
Let's see DeleteActivity in detail
Note application in a round form factor device
Note application in a square form factor device
Summary
Let us Help Capture What is on Your Mind - Saving Data and Customizing the UI
Wear-note-2
Advantages of Realm
Disadvantages of Realm
Re-structuring the code and dependencies
Working on the Wear User Interface
Let's get started working on the Wear-note-2 user interface
Better fonts for better reading
Writing custom layouts for better UX
Summary
Measure Your Wellness - Sensors
Conceptualizing the application
Enlisting the available sensors in Wear
Accuracy of sensors
Battery consumption
Doze mode
Creating a project
Adding a drawer menu
Creating a navigation drawer adapter
Creating fragments
Summary
Measuring Your Wellness and Syncing Collected Sensor Data
Collecting Wear sensors' data
Completed WearStepService class
Switching back to the Wear module
Conceptualizing the application
Recyclerview Adapter
Completed HistoryActivity Class
Summary
Ways to Get Around Anywhere - WearMap and the GoogleAPIclient
Let's get started with creating WearMap
The Google API console
The Google API client
Configuring the project for functionalities
Getting users' location information with the help of GoogleApiClient
GeoSpatial data using GeoCoder
Infowindow adapter
Custom DialogFragment for taking notes about the location
Configuring SQLite and saving the markers
Schema and contract
Saving data in SQLite
Difference between a standalone map and mobile-synced map application
Identifying the app as standalone
Sharing data between a Wear app and phone app
Detecting your application from another device
Specifying capability names to detect your apps
Detecting and guiding the user to install a corresponding phone app
Keeping your application active on a Wear device
Configuring WAKE_LOCK for your application
Understanding fully interactive mode and lite mode
Summary
Ways to Get Around Anywhere - UI controls and More
Changing marker color and customizing
Dragging the marker and updating the location
InfoWindow click event
The UI controls
Types of Maps
Streetview in Wear application
Best practices
Summary
Let us Chat in a Smart Way - Messaging API and More
Installing Firebase
Conceptualizing the chatting application
Understanding Data Layer
Data Layer events
Capability API
Mobile app implementation
Wear App implementation
Summary
Let us Chat in a Smart Way - Notifications and More
Firebase functions
Messaging service class
Summary
Just a Face for Your Time - WatchFace and Services
The CanvasWatchFaceService class and registering your watch face
The CanvasWatchFaceService.Engine class
Writing your own watch face
Handling tap events and gestures
Supporting different form factors
Understanding watch face elements and initializing them
Common issues
Interactive watch faces
Summary
More About Wear 2.0
Standalone applications
Identifying an app as a standalone
Standalone apps storage
Detecting wear app on another device
Advertise capability
Retrieving the nodes with the required capability
Detecting and guiding the user to install a phone app
Getting just the important information
Cloud messaging
Complications API
Complication data provider
Adding complications to a watch face
Receiving data and rendering complications
Allowing users to choose data providers
User interactions with complications
Permissions for complication data
Opening the provider chooser
Understanding different navigation for wear
Implementation
Single-page navigation drawer
Notifications in wear 2.0
Inline action
Expanded notifications
Best practices for expanded notifications
Bridging mode for notifications
Wear 2.0 input method framework
Invoking input method for wear
Wrist gestures
Best practices for using gestures in apps
Authentication protocols
App distribution
Publish your first wear app
Summary
Android Wear 2.0 is a powerful platform for wearable smart devices. Wear 2.0 enabled close to 72 percent new device activation in the wearable device market from the day Wear was announced. Google is working with multiple iconic brands to bring the best user experience to smart watches. Continuous improvement in the Wear hardware for new devices in the market shows the potential Wear devices can offer. Google introduced a whole new way of experiencing wearable technology with material design, standalone applications, watch face innovations, and more.
The Wear platform is becoming more popular, and Android developers can reap the benefits of improving their ability to program for Wear devices.
This book helps to create five Wear applications, with comprehensive explanations. We start with making a wearable note taking application by exploring Wear-specific user interface components and building a Wear map application with the ability to persist a quick note on the map. We will build a complete chat application with a companion mobile application. We will also build a health and fitness application to monitor pulse rate, a reminder to drink water, and so on, and also write a digital watch. We will complete the book by exploring the capabilities of the Wear 2.0 platform.
Have fun building great wear applications.
Chapter 1, Getting You Ready to Fly - Setting Up Your Development Environment, teaches you to write your first Wear application, explores the essential UI components specific to Wear applications, and discusses Android Wear design principles.
Chapter 2, Let us Help Capture What is on Your Mind - WearRecyclerView and More, covers WearableRecyclerView and the WearableRecyclerView adapter, and SharedPreferences, BoxInsetLayout, and the animated DelayedConfirmation.
Chapter 3, Let us Help Capture What is on Your Mind - Saving Data and Customizing the UI, explores the integration of the Realm database and custom fonts, UI updates, and finalizing the project.
Chapter 4, Measure Your Wellness - Sensors, showcases the accuracy of the sensors, battery consumption, Wear 2.0 doze mode, material design, and so on.
Chapter 5, Measure Your Wellness - Syncing Collected Sensor Data, focuses on syncing collected sensor data, collecting sensor data from a Wear device, processing the received data to find calories and distance, sending data to a Wear application from a mobile application, Realm DB integration, WearableRecyclerView, and CardView.
Chapter 6, Ways to Get Around Anywhere - WearMap and GoogleAPIclient, explains the Developer API console; the Maps API Key; and SHA1 Fingerprint, SQlite integration, Google Maps, the Google API Client, and Geocoder.
Chapter 7, Ways to Get Around Anywhere - UI controls and More, looks at understanding UI controls, marker controls, map zoom controls, StreetView in Wear, and best practices.
Chapter 8, Let us Chat in a Smart Way - Messaging API and More, discusses configuring Firebase for your mobile application, creating a user interface, understanding the messaging API, working with Google API Client, and building a Wear module.
Chapter 9, Let us Chat in a Smart Way - Notifications and More, covers Firebase functions, notifications, material design Wear app Wear 2.0 input method framework, and so on.
Chapter 10, Just a Face for Your Time - WatchFace and Services, outlines CanvasWatchFaceService and registering a watch face, CanvasWatchFaceService.Engine and callbacks, watch face elements and initializing them writing the watch face, and handling gestures and tap events.
Chapter 11, More About Wear 2.0, explores a standalone application, curved layout and more UI components the Complications API, different navigations and actions, wrist gestures, input method framework, and distributing Wear apps to the Play Store.
To be able to follow with this book, you need a computer with the latest Android Studio version installed. You need internet to set up all the required SDK for Wear development. If you have a Wear device to test the application, that would be good; otherwise, Android Wear emulators will do the magic.
This book is for Android developers who already have a strong understanding of programming and developing apps in Android. This book helps the reader advance from being an intermediate-level to an expert-level Android developer, by adding Wear development skills to their knowledge.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Specific commands or tools from the interface will be identified as follows:
Select the Save button.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."
A block of code is set as follows:
compile 'com.google.android.support:wearable:2.0.0' compile 'com.google.android.gms:play-services-wearable:10.0.1' provided 'com.google.android.wearable:wearable:2.0.0'When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
<?"1.0" encoding="utf-8"?> <android.support.wearable.view.BoxInsetLayout xmlns:android"http://schemas.android.com/apk/res/android" xmlns:app"http://schemas.android.com/apk/res-auto" xmlns:tools"http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.ashok.packt.wear_note_1.MainActivity" tools:deviceIds="wear"> </android.support.wearable.view.BoxInsetLayout>Any command-line input or output is written as follows:
adb connect 192.168.1.100New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Let the default selected template be the Wear application code stub Always On Wear Activity."
Warnings or important notes appear like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Android-Wear-Projects. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
The culture of Wearing a utility that helps us to perform certain actions has always been part of a modern civilization. Wrist watches for human beings have become an augmented tool for checking the time and date. Wearing a watch lets you check the time with just a glance. Technology has taken this watch-wearing experience to the next level. The first modern Wearable watch was a combination of a calculator and a watch, introduced to the world in 1970. Over the decades, advancements in microprocessors and wireless technology have led to the introduction of a concept called ubiquitous computing. During this time, most leading electronics industry start-ups started to work on their ideas, which has made Wearable devices very popular.
Tech giant companies, such as Google, Apple, Samsung, and Sony, have joined the force of the Wearable devices era. They have introduced their competitive Wearable products, which are extremely successful in the Wearable device market. More interestingly, Google's Android Wear is powerful, follows the same Android smartphone development practices, and has a very good developer community compared to Apple Watch OS and Samsung's Tizen OS developer community.
Google announced Android Wear in March 2014. Since then, Android Wear as a smartwatch and Wearable software platform has evolved. Google's continuous advancement in designing and user experience have resulted in a new generation of the Android Wear operating system, which has the ability to handle biometric sensors like never before with more features in the platform; Google calls it Android Wear 2.0.
Android Wear 2.0 will cause a lot of excitement in app development with remarkably competitive features to develop. Android Wear 2.0 allows a developer to build and carve his idea specific to Android Wear; there is no need to pair a watch and mobile app. Google calls it a standalone application. Android Wear 2.0 introduces a new way to input within the Android watch: a new application programming interface called Complications, which allows watch faces to display vital information from biometrics and other sensors. New updated notifications support for Android Wear 2.0 will help users and developers to present notifications in a more comprehensive manner.
In this chapter, we will explore the following:
Android Wear design principles
Exploring essential UI components specific to Wear apps
Setting up a development environment for Wear apps development
Creating your first Android Wear application
Designing a Wear application is different than designing a mobile or tablet application. The Wear operating system is very lightweight and has a specific set of jobs to accomplish by sharing the right information with the Wearer.
General Wear principles are Timely, Glanceable, Easy to Tap, Time-Saving.
Timely
Giving the right information at the right time.
Glanceable
Keeping the Wear application user interface clean and uncluttered.
Easy to Tap
The actions users will click on should have the right spacing and size of the picture.
Time-Saving
Creating the best application flows that do tasks quickly.
For any Wear application, we need the proper building blocks to control the business logic of the application and other architectural implementation. The following are the scenarios for developing a Wear application to help us to carve the wear application better:
Defining layouts
Creating lists
Showing confirmations
Wear navigation and actions
Multifunction buttons
Wearable applications can use the same layouts that we use in handheld Android device programming but with specific constraints for Wear applications. We should not do heavy processing actions similar to handheld Android devices in Wear applications and expect a good user experience.
An application designed for a round screen will not look great on square Wear devices. To resolve this, the Android Wear support library comes with the following two solutions:
BoxInsetLayout
Curved Layout
We can provide different resources to allow Android to detect the shape of the Android Wear at runtime.
Lists let the user select an item from a set of items. In the legacy Wear, 1.x API WearableListView helped programmers to build lists and custom lists. Wearable UI library now has WearableRecyclerView with curvedLayout support and has the best implementation experience in Wear devices.
We can add gestures and other magnificent functionalities:
In this subchapter, let's explore the commonly used Wear-specific UI components. In Wear application programming, we can use all the components that we use in mobile app programming, but how we accommodate the visual appearance of components in the Wear device needs to be well thought of before using it.
WatchViewStub: WatchViewStub helps in rendering the views for different form factors of Wearable devices. If your application is being installed on a round watch device, WatchViewStub will load the specific layout configuration for round watches. If it is square, it will load the square layout configuration:
<?xml version="1.0" encoding="utf-8"?><
android.support.wearable.view.WatchViewStub
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/watch_view_stub" android:layout_width="match_parent" android:layout_height="match_parent"
app:rectLayout="@layout/rect_activity_main" app:roundLayout=
"@layout/round_activity_main"
tools:context="com.ashokslsk.wearapp.MainActivity" tools:deviceIds="wear"></android.support.wearable.view.WatchViewStub>
WearableRecyclerView: WearableRecyclerView is the implementation of recyclerview specific to wearable devices. It provides a flexible view for datasets in the Wearable device viewport. We will explore WearbaleRecyclerView in detail in the coming chapters:
<
android.support.wearable.view.WearableRecyclerView
android:id="@+id/recycler_launcher_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="vertical" />
CircledImageVIew: An Imageview surrounded by a circle. A very handy component for presenting the image in round form factor Wearable devices:
<?xml version="1.0" encoding="utf-8"?><
android.support.wearable.view.CircledImageView
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/circledimageview" app:circle_color="#2878ff" app:circle_radius="50dp" app:circle_radius_pressed="50dp" app:circle_border_width="5dip" app:circle_border_color="#26ce61" android:layout_marginTop="15dp" android:src="@drawable/skholinguaicon" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" />
BoxInsetLayout: This Layout extends directly to Framelayout and it has the ability to recognize the form factor of the Wearable device. Shape-aware FrameLayout can box its children in the center square of the screen:
<
android.support.wearable.view.BoxInsetLayout
xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.example.ranjan.androidwearuicomponents.BoxInsetLayoutDemo"><TextView android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_box="all" /></
android.support.wearable.view.BoxInsetLayout
>
After the Wear 2.0 release, a few components were deprecated for an immersive activity experience and Google strictly prohibits using them; we can still use all the components that we know in Android programming.
Compared to confirmations in handheld Android devices, in Wear applications, confirmations should occupy the whole screen or more than what handheld devices show as a dialogue box. This ensures users can see these confirmations at one glance. The Wearable UI library helps in displaying confirmation timers and animated timers in Android Wear.
A DelayedConfirmationView is an automatic confirmation view based on the timer:
<
android.support.wearable.view.DelayedConfirmationView
android:id
"@+id/delayed_confirm"
android:layout_width
"40dp"
android:layout_height
"40dp"
android:src
"@drawable/cancel_circle"
app:circle_border_color
"@color/lightblue"
app:circle_border_width
"4dp"
app:circle_radius
"16dp"
>
</
android.support.wearable.view.DelayedConfirmationView
>
In the new release of Android Wear, the Material design library adds the following two interactive drawers:
Navigation drawer
Action drawer
Lets user switch between views in the application. Developers can allow the drawer to be opened anywhere within the scrolling parent's content by setting the setShouldOnlyOpenWhenAtTop() method to false:
<
android.support.wearable.view.drawer.WearableNavigationDrawe
r
android:id
"@+id/top_drawer"
android:layout_width
"match_parent"
android:layout_height
"match_parent"
android:background
"@android:color/holo_red_light"
app:navigation_style
"single_page"
/>
The action drawer gives access to easy and common actions in your application. By default, action drawer appears at the bottom of the screen and provides specific actions to users:
<android.support.wearable.view.drawer.WearableActionDrawer
android:id
"@+id/bottom_drawer"
android:layout_width
"match_parent"
android:layout_height
"match_parent"
android:background
"@android:color/holo_blue_dark"
app:show_overflow_in_peek
"true"
/>
In addition to the power button, Android Wear supports another button called the multifunction button on the device. The Wearable support library provides API for determining the multifunction buttons included by the manufacturer:
@Override
// Activity
public
boolean
onKeyDown
(
int
keyCode
,
KeyEvent
event
){
if
(
event
.
getRepeatCount
()
0
)
{
if
(
keyCode
KeyEvent
.
KEYCODE_STEM_1
)
{
// Do stuff
return
true
;
}
else
if
(
keyCode
KeyEvent
.
KEYCODE_STEM_2
)
{
// Do stuff
return
true
;
}
else
if
(
keyCode
KeyEvent
.
KEYCODE_STEM_3
)
{
// Do stuff
return
true
;
}
}
return
super
.
onKeyDown
(
keyCode
,
event
);
}
Visit https://developer.android.com/training/wearables/ui/index.html for any sort of query that you might have on design guidelines for Wear device programming.
In this section, we will set up a development environment for Wear application development.
Prerequisites
Your favorite operating system (Windows, macOS, or Linux)
Determine whether you have the latest JRE installed on your operating system
Install the latest version of JDK or Open JDK
Install the latest version of Android Studio (at the time of writing this book, the latest version is 2.2.3 and any newer version should be fine)
Visit https://developer.android.com/studio/index.html to download the latest version of Android Studio. Google highly recommends using Android Studio for all Android application development, since Android Studio has tight integration with Gradle and useful Android APIs:
After the Android Studio installation, it's now time to download the necessary SDK in the SDK Platforms tab in SDK Manager. Install one complete version of Android; for the scope of this book, we will install Android 7.1.1 API level 25:
After the successful installation of the SDK of Nougat 7.1.1 API level 25, under the SDK Tools tab, make sure you have installed the following components, as shown in the following screenshot:
Android Support Library
Google Play services
Google Repository
Android Support Repository
Google releases updates on IDE and SDK Tools frequently; keep your development environment up-to-date.
Note: if you plan to make your application available in China, then you must use the special release version 7.8.87 of the Google Play services client library to handle communication between a phone and watch: https://developer.android.com/training/wearables/apps/creating-app-china.html
Visit the following link to check the update Release Notes on SDK Tools: https://developer.android.com/studio/releases/sdk-tools.html.
Updating your IDE from the stable channel is highly recommended. Updates for Android Studio are available on four different channels:
Canary channel
Dev channel
Beta channel
Stable channel
Canary channel: The Android Studio engineering team works continuously to make Android Studio better. In this channel, every week there will be an update release, and it will include new functionality changes and improvements; you can check those changes in the release notes. But updates from this channel are not recommended for application production.
Dev Channel: On this channel, a release happens after a complete round of internal testing from the Android Studio team.
Beta channel: On this channel, updates are totally based on stable Canary builds. Before publishing these builds to a stable channel, Google releases them in the beta channel to get developer feedback.
Stable Channel: Are the official stable releases of the Android Studio and will be available to download on Google's official page http://developer.android.com/studio.
By default, Android Studio receives updates from a stable channel.
In this section, let's understand the essential steps required to create your first Wear project.
The following picture is the initial interface of Android Studio. In this window, one can import legacy ADT Android projects, configure the Android SDK, and update Android Studio.
Android Studio welcome window with basic controls for getting started:
Click on the Start a new Android Studio project option in the Android Studio window. You will be prompted by another window with project details.
The following screenshot shows the window that allows users to configure their project details, such as project name, Package name, and whether the project needs native C++ support:
You can name your project as you wish. After you have chosen your project name and your project local system location, you can press the Next button in the window, which brings up another window with a few configuration queries, as shown in the following screenshot:
In this window, you can choose to write a standalone Wear application if you uncheck the Phone and Tablet option. In this way, you will see only Wear application templates:
Now, Android Studio templates prompt only Android Wear activity templates with the following set of options:
Add No Activity
Always On Wear Activity
Blank Wear Activity
Display Notification
Google Maps Wear Activity
Watch Face
The activity template chooser helps you to access the default boilerplate codes, which are already templatized and can be used directly in projects:
To create the first project, we will choose Blank Wear Activity and click on the Next button in the window. Android Studio will prompt another window for creating the name of the activity and layout file. In this template, the two form factors of Android Wearable devices, which are mostly round and square shapes, are prepopulated with the boilerplate code stub:
When your project is ready to be created, click on the Finish button. After clicking on Finish, Android Studio will take a few moments to create the project for us.
Way to go! You have now created a working boilerplate code for the Android Wear standalone application without the phone companion application. When successfully created, you will see the following files and codes added to your project by default:
If your SDK is not updated with API level 25, you might see the Wear option in the Android Studio project creating prompts with Android Wear support library 1.x; you can update this in the Wear module Gradle file with the following dependency:
compile 'com.google.android.support:wearable:2.0.0'
The process of creating a Wear emulator is very similar to creating a phone emulator.
In the AVD manager, click on the Create Virtual Device... button:
Choose the required form factor emulator according to your application needs. Now, let's create the Android Wear square emulator:
After selecting the right emulator for your Wear, you will get another prompt to choose the Wear operating system. Let's choose the API Level 25Nougat emulator, as shown in the following screenshot:
The last prompt asks for the emulator name and other orientation configurations based on your needs:
Way to go! Now, we have successfully created a square form factor emulator for the project. Let's run the project that we have created in the emulator:
Google recommends developing Wear apps in the actual hardware device to have the best user experience. However, working on emulators has the benefit of creating different screen form factors to check the application's rendering.
Open the settings menu on the Wear device
Go to About device
Click on the build number seven times to enable developer mode
Now enable ADB debugging on the watch
You can now connect the Wear device directly to your machine with the USB cable. You can debug your applications over Wi-Fi and Bluetooth with the following setups.
Make sure your watch has the developer options enabled. Debugging over Wi-Fi is possible only when the Wear device and machine are connected to the same network.
In the Wear device developer option, tap on Debug over Wi-Fi
The watch will display its IP address (for example, 192.168.1.100). Keep a reference; we need this for the next step.
Connect the debugger to the device
Using the following command, we can attach the actual device to the ADB debugger:
adb connect
192.168
.
1.100
We need to ensure debugging is enabled in developer options, as follows:
Enable Debug over Bluetooth
Install the companion app on the phone (download it from
https://play.google.com/store/apps/details?id=com.google.android.wearable.app&hl=en
)
Go to settings in the companion app
Enable debugging over Bluetooth
Connect the phone to the machine through the cable
You can use the following commands to establish the connection:
adb forward tcp
:
4444
localabstract
:/
adb
-
hubadb connect
127.0
.
0.1
:
4444
In your Android Wear, just allow ADB Debugging when it asks.
Now that we have a working setup of our development environment, let's understand the basic Android Wear-specific UI components.
