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 – shake detection using the accelerometer sensor


One of the most common use cases of the accelerometer sensor is to detect the shaking of the phone. Shaking can act as a valuable input for the apps, especially when the phone screen is off. For example, a lot of music player apps allow you to change the songs just by shaking the phone. In our example, we will play a small audio MP3 file when the phone shake is detected using the accelerometer sensor:

  1. As the first step, we create the necessary infrastructure to get the values from the accelerometer sensor. We will create a ShakeDetectionActivity and follow the standard steps for getting values from a sensor. We will select the sensor type for TYPE_ACCELEROMETER in the getDefaultSensor() method of SensorManager and initiate the MediaPlayer object with the audio MP3 file kept in the raw folder inside the onCreate() method of the activity. As a standard practice, we will register the listener in onResume()and un-register it in...