34,79 €
Take your Android applications to the next level of interactivity by exploring the wide variety of Android sensors
This book is targeted at Android developers who want to get a good understanding of sensors and write sensor-based applications, or who want to enhance their existing applications with additional sensor functionality. A basic knowledge of Android development is required
Android phones available in today's market have a wide variety of powerful and highly precise sensors. Interesting applications can be built with them such as a local weather app using weather sensors, analyzing risky driving behavior using motion sensors, a fitness tracker using step-counter sensors, and so on. Sensors in external devices such as Android Watch, Body Analyzer & Weight Machine, Running Speed Cell, and so on can also be connected and used from your Android app running on your phone.
Moving further, this book will provide the skills required to use sensors in your Android applications. It will walk you through all the fundamentals of sensors and will provide a thorough understanding of the Android Sensor Framework. You will also get to learn how to write code for the supportive infrastructure such as background services, scheduled and long running background threads, and databases for saving sensor data. Additionally, you will learn how to connect and use sensors in external devices from your Android app using the Google Fit platform.
By the end of the book, you will be well versed in the use of Android sensors and programming to build interactive applications.
A step-by-step and easy-to-follow guide that focuses on utilizing sensors to perform certain tasks. After covering the fundamentals in the first chapter, the book develops the concepts by building a real-world, sensor-based application in subsequent chapters.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 214
Veröffentlichungsjahr: 2016
Copyright © 2016 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: April 2016
Production reference: 1270416
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78528-550-9
Author
Varun Nagpal
Copy Editor
Angad Singh
Reviewers
Ahmed Mubarak Al-Haiqi
José Juan Sánchez Hernández
Project Coordinator
Judie Jose
Commissioning Editor
Ashwin Nair
Proofreader
Safis Editing
Acquisition Editor
Tushar Gupta
Indexer
Mariammal Chettiyar
Content Development Editor
Pooja Mhapsekar
Graphics
Abhinash Sahu
Technical Editor
Vivek Arora
Production Coordinator
Arvindkumar Gupta
Varun Nagpal has been developing mobile apps since 2005 and has developed and contributed to more than 100 professional apps and games on various platforms, such as Android, iOS, Blackberry, and J2ME. Android app development has been his main area of expertise, and he has developed apps for a wide variety of Android devices, such as Android phones, tablets, watches, smart TVs, Android Auto, and Google Glass.
He moved to Chicago in late 2013, and since then, he has become a seasoned mobile architect. He has worked in different roles (mobile architect, technical lead, senior developer, and technical consultant) for a variety of various global clients (Allstate, Verizon, AT&T, Sydbank Denmark, SiS Taiwan, Chams PLC Nigeria, and Nandos South Africa) in order to implement their mobile solutions. He has SCJP (Core Java) and SCWD (JSP and Servlets) certifications from Sun Microsystems and MCP (C#) and MCTS (ASP.NET) certifications from Microsoft. You can find his blogs on mobile technology and white papers written by him on his website at http://www.varunnagpal.com/.
When he's not working, Varun can be found meditating or playing the flute. He also loves to develop meditation apps and fun games in his free time. He has developed about 40 meditation apps and games available on Google Play (https://play.google.com/store/apps/developer?id=Creative.Software.Studio) and the Apple App Store (https://itunes.apple.com/us/artist/creative-software-studio/id574745824) under the name of Creative Software Studio, his part-time start-up company (http://creativesoftwarestudio.com/).
I would like to thank my wife, Ankita, for supporting me at every step, and I want to apologize to my one-year-old daughter for not giving her enough time while writing this book. I would also like to acknowledge my parents for their encouragement. Finally, I want to thank the editor, each member of the Packt Publishing team, and the technical reviewers for the effort and enthusiasm they showed while working on this book.
Ahmed Mubarak Al-Haiqi received his PhD (he investigated sensor-based side channels on Android) and MEng (in computer and communications engineering) degrees from the National University of Malaysia. Before pursuing his graduate studies, he worked as a database developer for several years with governmental organizations in Aden, Yemen, where he completed a BEng and majored in computer engineering and science. He is currently involved in conducting academic research on mobile security, machine learning, next generation networking trends, as well as interdisciplinary topics.
José Juan Sánchez Hernández received an MSc degree in computer science from the University of Almería in 2008. He is a member of the Supercomputing-Algorithms Research Group at the University of Almería, and he is currently working toward a PhD in the area of image coding and transmission.
In his spare time, he enjoys designing and developing native mobile apps for Android, experimenting and making stuff with Arduino and Raspberry Pi, and learning new things. He is also the cofounder of Android Almería Developers Group and an active member of HackLab Almería, where he organizes programming talks and hackathons.
He participated as a mentor in the Google Summer of Code 2015 with the P2PSP organization. You can find out more about him at http://josejuansanchez.org.
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://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Welcome to Android Sensor Programming By Example. This book will provide you the skills required to use sensors in your Android applications. It will walk you through all the fundamentals of sensors and will provide a thorough understanding of the Android Sensor Framework. This book will cover a wide variety of sensors available on the Android Platform. You will learn how to write code for the infrastructure (service, threads, database) required to process high volumes of sensor data. This book will also teach you how to connect and use sensors in external devices (such as Android Wear) from the Android app using the Google Fit platform.
You will learn from many real-world sensor-based applications such, as the Pedometer app to detect daily steps, the Weather app to detect temperature, altitude, absolute and humidity, the Driving app to detect risky driving behavior, and the Fitness tracker app to track heart rate, weight, daily steps, and calories burned.
Chapter 1, Sensor Fundamentals, provides you a thorough understanding of the fundamentals and framework of Android sensors. It walks you through the different types of sensors and the sensor coordinate system in detail.
Chapter 2, Playing with Sensors, guides you through various classes, callbacks, and APIs of the Android Sensor framework. It walks you through a sample application, which provides a list of available sensors and their values and individual capabilities, such as the range of values, power consumption, minimum time interval, and so on.
Chapter 3, The Environmental Sensors – The Weather Utility App, explains the usage of various environment sensors. We develop a weather utility app to compute altitude, absolute humidity, and dew point using temperature, pressure, and relative humidity sensors.
Chapter 4, The Light and Proximity Sensors, teaches you how to use proximity and light sensors. It explains the difference between wakeup and non-wakeup sensors and explains the concept of the hardware FIFO sensor queue. As a learning exercise, we develop a small application that turns on/off a flashlight using a proximity sensor, and it also adjusts screen brightness using a light sensor.
Chapter 5, The Motion, Position, and Fingerprint Sensors, explains the working principle of motion sensors (accelerometer, gyroscope, linear acceleration, gravity, and significant motion), position sensors (magnetometer and orientation), and the fingerprint sensor. We learn the implementation of these sensors with the help of three examples. The first example explains how to use the accelerometer sensor to detect phone shake. The second example teaches how to use the orientation, magnetometer, and accelerometer sensors to build a compass, and in the third example, we learn how to use the fingerprint sensor to authenticate a user.
Chapter 6, The Step Counter and Detector Sensors – The Pedometer App, explains how to use the step detector and step counter sensors. Through a real-world pedometer application, we learn how to analyze and process the accelerometer and step detector sensor data to develop an algorithm for detecting the type of step (walking, jogging, sprinting). We also look at how to drive the pedometer data matrix (total steps, distance, duration, average speed, average step frequency, calories burned, and type of step) from the sensor data.
Chapter 7, The Google Fit Platform and APIs – The Fitness Tracker App, introduces you to the new Google Fit platform. It walks you through the different APIs provided by the Google Fit platform and explains how to request automated collection and storage of sensor data in a battery-efficient manner without the app being alive in the background all the time. As a learning exercise, we develop a fitness tracker application that collects and processes the fitness sensor data, including the sensor data obtained from remotely connected Android Wear devices.
Bonus Chapter, Sensor Fusion and Sensor – Based APIs (the Driving Events Detection App), guides you through the working principle of sensor-based Android APIs (activity recognition, geo-fence, and fused location) and teaches you various aspects of sensor fusion. Through a real-world application, you will learn how to use multiple sensors along with input from sensor-based APIs to detect risky driving behavior. Through the same application, you will also learn how to develop the infrastructure (service, threads, and database) required to process high volumes of sensor data in the background for a longer duration of time. This chapter is available online at the link https://www.packtpub.com/sites/default/files/downloads/SensorFusionandSensorBasedAPIs_TheDrivingEventDetectionApp_OnlineChapter.pdf
You will need a Windows or a Mac system with Android Studio to run the examples in this book. All the examples are developed using Android Studio, but you can still execute them on Eclipse with ADT by exporting them to an Eclipse project structure. You are encouraged to run all the examples in the book on a real Android device as there is no official support for sensors in the Android emulator. An open source sensor simulator is available, and it will simulate some of the sensors on the Android emulator in real time. It is available at https://github.com/ezyang/SensorSimulator.
This book is targeted at Android developers who want to thoroughly understand sensors and write sensor-based applications or want to enhance their existing applications with additional sensor functionality. A basic knowledge of Android development is required.
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 https://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:
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
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.
In this chapter, we will understand the fundamentals of sensors and explore what the sensor world looks like from an Android perspective. We will also look at the classes, interfaces, and methods provided by the Android platform to access sensors. This chapter will also focus on the standards and best practices for using Android sensors.
You will learn the following topics in this chapter:
In simple words, sensors measure a particular kind of physical quantity, such as force acting on device, light falling on a surface, or the temperature in a room. These are examples of a basic physical quantity that sensors can measure. Most Android phones come with advance sensors that can measure valuable information such as relative humidity, atmospheric pressure, magnetic field, steps taken, the rate of rotation of a device on the x, y, and z axes, proximity to an object, and many more. The majority of the sensors are Micro Electro Mechanical Sensors (MEMS), which are made on a tiny scale (in micrometers), usually on a silicon chip, with mechanical and electrical elements integrated together.
The basic working principle behind MEMS is to measure the change in electric signal originating due to mechanical motion. This change in electric signals is converted to digital values by electric circuits. The accelerometer and gyroscope are the main examples of MEMS. Most of the sensors in an Android phone consume minimal battery and processing power. We will discuss all the important sensors in detail in the coming chapters.
Sensor can be broadly divided into the following two categories:
The Android platform doesn't make any distinction when dealing with physical sensors and synthetic sensors. The distinction is mostly theoretical to understand the origin of the sensor values.
Sensor values can be broadly divided into the following three categories:
The Android platform supports mainly three broad categories of sensors: the motion, position, and environment-based sensors. This categorization is done based on the type of physical quantity detected and measured by the sensors.
Motion sensors are responsible for measuring any kind of force that could potentially create motion in the x, y, and z axes of the phone. The motion could be either a linear or angular movement in any direction. This category includes accelerometers, gravity, gyroscope, and rotational vector sensors. Most of these sensors will have values in the x, y, and z axes, and the rotational vector will especially have extra value in the fourth axis, which is the scalar component of the rotation vector.
The following table summarizes the motion sensor usage, types, and power consumption:
Sensor
Type
Value
Underlying Sensors
Description
Common Usage
Power Consumption
Accelerometer
Physical
Raw
Accelerometer
This measures the acceleration force along the x, y, and z axes (including gravity). Unit: m/s2
It can be used to detect motion such as shakes, swings, tilt, and physical forces applied on the phone.
Low
Gravity
Synthetic
Fused
Accelerometer, Gyroscope
This measures the force of gravity along the x, y, and z axes. Unit: m/s2
It can be used to detect when the phone is in free fall.
Medium
Linear Acceleration
Synthetic
Fused
Accelerometer, Gyroscope
It measures the acceleration force along the x, y, and z axes (excluding gravity). Unit: m/s2
It can be used to detect motion such as shakes, swings, tilt, and physical forces applied on phone.
Medium
Gyroscope
Physical
Raw, Calibrated
Gyroscope
This measures the rate of rotation of the device along the x, y, and z axes. Unit: rad/s
It can be used to detect rotation motions such as spin, turn, and any angular movement of the phone.
Medium
Step Detector
Synthetic
Calibrated
Accelerometer
This detects walking steps.
It can be used to detect when a user starts walking.
Low
Step Counter
Synthetic
Calibrated
Accelerometer
It measures the number of steps taken by the user since the last reboot while the sensor was activated
It keeps track of the steps taken by the user per day.
Low
Significant Motion
Synthetic
Calibrated
Accelerometer
