Android Sensor Programming By Example - Varun Nagpal - E-Book

Android Sensor Programming By Example E-Book

Varun Nagpal

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Take your Android applications to the next level of interactivity by exploring the wide variety of Android sensors

About This Book

  • Get a thorough understanding of the fundamentals and framework of Android sensors.
  • Acquire knowledge of advance sensor programming, and learn how to connect and use sensors in external devices such as the Android Watch, Polar heart rate monitors, Adidas speed cells, and so on.
  • Learn from real-world sensor-based applications such as the Pedometer app to detect daily steps, the Driving app to detect driving events, and the Professional Fitness tracker app to track heart rate, weight, daily steps, calories burned, and so on.

Who This Book Is For

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

What You Will Learn

  • Learn about sensor fundamentals, different types of sensors, and the sensor co-ordinate system
  • Understand the various classes, callbacks, and APIs of the Android Sensor framework
  • Check all the available sensors on an Android device and know their individual capabilities—for example, their range of values, power consumption, and so on.
  • Implement sensor fusion using two or more sensors together and learn to compensate for the weakness of one sensor by using the strength of another
  • Build a variety of sensor based, real-world applications such as Weather, Pedometer, Compass, Driving Events Detection, Fitness Tracker, and so on.
  • Get to know about wake up and non-wake up sensors, wake locks, and how to use sensor batch processing along with the sensor hardware FIFO queue
  • Develop efficient battery and processor algorithms using raw sensor data to solve real-world problems
  • Connect to a variety of remote sensors such as body weight measurement and body fat percentage measurement using the Google Fit platform from your Android app

In Detail

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.

Style and approach

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:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 214

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Android Sensor Programming By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Why subscribe?
Free access for Packt account holders
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
1. Sensor Fundamentals
What are sensors?
Types of sensors
Types of sensor values
Motion, position, and environmental sensors
Motion sensors
Position sensors
Environmental sensors
Sensors' coordinate system
Android Sensor Stack
Components of the sensor framework
SensorManager
SensorEventListener
Sensor
SensorEvent
Sensor's sampling period, power, and battery consumption
The reporting modes of sensors
Dealing with specific sensor configuration
Checking the availability of the sensor at runtime
Declaring the sensor as mandatory feature
Sensor availability based on the Android API level
Best practice for accessing sensors
Summary
2. Playing with Sensors
Understanding the sensor framework callbacks
Seeing the big picture
Time for action - using sensors in the foreground activity
What just happened?
Time for action – listing the available sensors on a device
What just happened?
Time for action – knowing individual sensors' capabilities
What just happened?
Time for action – getting the sensor values and updating the user interface
What just happened?
Time for action – processing the sensor values in the background service
The phone handling algorithm
What just happened?
Summary
3. The Environmental Sensors – The Weather Utility App
The weather utility app's requirements
Understanding environmental sensors
Time for action – using the temperature sensor
What just happened?
Getting air pressure from the phone's pressure sensor
Time for action – calculating the altitude using the pressure sensor
What just happened?
Getting relative humidity from the phone's humidity sensor
Time for action - calculating the dew point and absolute humidity
What just happened?
Time for action – comparing the temperature, humidity, and pressure values from web services to phone sensors
Third-party web service – open weather map
Using Google Play Services Location API and AsyncTask
What just happened?
Summary
4. The Light and Proximity Sensors
Understanding the light and proximity sensors
The automatic torch light and screen brightness app requirements
Time for action – turning the torch light on and off using the proximity sensor
What just happened?
Time for action – adjusting the screen brightness using the light sensor
What just happened?
Wake locks, wakeup sensors, and the FIFO queue
Wakeup and non-wakeup sensors
The sensor's hardware FIFO queue
Summary
5. The Motion, Position, and Fingerprint Sensors
Understanding motion-based sensors
The accelerometer sensor
The gyroscope sensor
The gravity sensor
The linear acceleration sensor
The significant motion sensor
Understanding position-based sensors
The magnetometer sensor
The orientation sensor
The fingerprint sensor
Time for action – shake detection using the accelerometer sensor
Time for action – the compass using orientation sensor and orientation APIs
Time for action – using the fingerprint sensor
What just happened?
Summary
6. The Step Counter and Detector Sensors – The Pedometer App
The pedometer app's requirements
Understanding the step counter and step detector sensors
The step counter sensor
The step detector sensor
Time for action – using the step counter sensor in activity
Time for action – maintaining step history with the step detector sensor
What just happened?
Understanding the walking, jogging, and running signatures using the accelerometer sensor's data
The walking signature using the accelerometer sensor
The jogging or fast walking signature using the accelerometer sensor
The running signature using the accelerometer sensor
The type of step detection algorithm
Making it battery- and CPU-efficient using sensor fusion
Scope for improvement
Time for action – type of step (walking, jogging, and running) detection using the accelerometer sensor
What just happened?
Summary
7. The Google Fit Platform and APIs – The Fitness Tracker App
The Google Fit platform
Google Fitness Store
REST APIs
Android Fitness APIs
Sensors API
Recording API
History API
Sessions API
Bluetooth Low Energy API
Config API
Platform basics
Data sources
Data types
Data point
Data set
Authorization and permission scopes
Registration with the Google developer console
Authorization from a user in the application
Fitness scopes
Installing and running time permissions
Fitness tracker app using fitness APIs
Fitness tracker application requirements and architecture
Time for action – working with live fitness data using the Sensors API
What just happened?
Time for action – recording fitness data in background using Recording API
What just happened?
Time for action – getting history fitness data using the History API
What just happened?
Asynchronous versus synchronous results callback
Summary

Android Sensor Programming By Example

Android Sensor Programming By Example

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

Credits

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

About the Author

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.

About the Reviewers

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.

www.PacktPub.com

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.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

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.

Preface

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.

What this book covers

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

What you need for this book

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.

Who this book is for

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.

Reader feedback

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.

Customer support

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.

Downloading the example code

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.

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:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

Errata

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

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.

Questions

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.

Chapter 1.  Sensor Fundamentals

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:

What are sensors?Different types of sensors and values.Individual sensor descriptions and their common usage.How to use sensor coordinate system?What is Android Sensor Stack?Understanding the Sensor framework APIs and classes.Understanding the sensor sampling period, frequency, and reporting mode.Specific sensor configuration and sensor availability based on the API level.Best practices to access and use sensors.

What are sensors?

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.

Types of sensors

Sensor can be broadly divided into the following two categories:

Physical Sensors: These are the actual pieces of hardware that are physically present on the device. They are also known as hardware sensors. Accelerometers, gyroscopes, and magnetometers are examples of physical sensors.Synthetic Sensors: These are not physically present on the device, and they are instead derived from one or more sensors. They are also called virtual, composite, or software sensors. Gravity, linear acceleration, and step detector are examples of synthetic sensors.

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.

Types of sensor values

Sensor values can be broadly divided into the following three categories:

Raw: These values are directly given by the sensor. The operating system simply passes these values to the apps without adding any correction logic. Accelerometers, proximity sensors, light sensors, and barometers are sensors that give raw values.Calibrated: These values are computed by the operating system by adding extra correction algorithms, such as drift compensation and removing bias and noise over the raw values given by sensors. Step detector, step counter, and significant motion are sensors that give calibrated values by using an accelerometer as their base sensor. The magnetometer and gyroscope are special kinds of sensor that give both raw and calibrated values.Fused: These values are derived from a combination of two or more sensors. Generally, these values are calculated by leveraging the strength of one sensor to accommodate the weaknesses of other sensors. Gravity and linear acceleration give fused values by using the accelerometer and gyroscope.

Motion, position, and environmental sensors

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

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