Book Image

Android Sensor Programming By Example

By : Varun Nagpal
Book Image

Android Sensor Programming By Example

By: Varun Nagpal

Overview of this book

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.
Table of Contents (13 chapters)
Android Sensor Programming By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface

Time for action – using the step counter sensor in activity


In this section, we will learn how to use the step counter sensor with a simple example. The good thing about the step counter is that, unlike other sensors, your app doesn't need to tell the sensor when to start counting the steps and when to stop counting them. It automatically starts counting as soon as the phone is powered on. To use it, we just have to register the listener with the sensor manager and then unregister it after using it. In the following example, we will be showing the total number of steps taken by the user since the last reboot (power on) of the phone in the android activity:

  1. We create a StepsCounterActivity, which implements the SensorEventListener interface so that it can receive the sensor events. We initiate the SensorManager and Sensor objects of the step counter, and we also check the sensor availability in the OnCreate() method of the activity. We register the listener in the onResume() method and unregistered...