Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Android Sensor Programming By Example
Android Sensor Programming By Example

Android Sensor Programming By Example: Take your Android applications to the next level of interactivity by exploring the wide variety of Android sensors

eBook
₹799 ₹2621.99
Paperback
₹3276.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Android Sensor Programming By Example

Chapter 2. Playing with Sensors

In this chapter, we will learn how to write our first sensor program. We will also understand the various callbacks, and how to use these callbacks in the foreground activity and background service. This chapter will also walk you through a basic algorithm developed using sensor values.

We will cover the following topics in this chapter:

  • Understanding various sensor framework callbacks
  • Using sensors in the foreground activity
  • Listing the available sensors on a device
  • Knowing individual sensors' capabilities
  • Getting the sensor values and updating the user interface
  • Monitoring sensor values in the background service

Understanding the sensor framework callbacks

The two most important callbacks of the sensor framework are the onSensorChanged() and onAccuracyChanged() methods. In order to write efficient sensor code, it's important to understand when these methods are called, and what processing we can do in them. These callbacks are methods of the SensorEventListnener interface, which needs to be implemented in the class where the callbacks are to be received:

onSensorChanged() is the first callback and has the following syntax:

@Override 
  public void onSensorChanged(SensorEvent event) { 
   } 

Depending on the type of reporting mode of the sensor, this method will be called, either at regular frequency (Continuous mode) or whenever there is a change in the value of the sensors from the previously reported value (On the change mode). The onSensorChanged() method provides the sensor values inside the float value[] array of the SensorEvent object. These sensor values are different...

Time for action - using sensors in the foreground activity

In this section, we will explore how to use sensors in the activity. This is the most basic and straightforward way of using sensors. Also, it's the most efficient way if your sensor functionality only ties to that activity:

  1. The first step is to implement our activity with the SensorEventListener interface so that our activity can receive SensorEvent through the onSensorChanged() method. The following code snippet shows the necessary import statements and the class declaration:
           import android.app.Activity; 
           import android.content.Context; 
           import android.hardware.Sensor; 
           import android.hardware.SensorEvent; 
           import android.hardware.SensorEventListener; 
           import android.hardware.SensorManager; 
           import android.os.Bundle; 
     
           public class SensorActivity extends Activity implements 
           SensorEventListener{ 
    
  2. Now, we will create the instance of SensorManager...

Time for action – listing the available sensors on a device

There are multiple sensors available on a device. In this section, we will learn how to get a list of all the available sensors. We will be populating the names of the available sensors in a list and will be displaying it on the screen using ListView.

  1. The following code block shows the declarations required by the activity. We don't need the SensorEventListener interface, as we will not be dealing with the values of the sensor. We declare ListView.ListAdapter, and SensorManager, along with the list of Sensor Objects to populate the list:
           public class SensorListActivity extends Activity 
           implements OnItemClickListener{ 
     
             private SensorManager mSensorManager; 
             private ListView mSensorListView; 
             private ListAdapter mListAdapter; 
             private List<Sensor> mSensorsList; 
    
  2. In the onCreate() method, we instantiate our SensorManager, ListView...

Time for action – knowing individual sensors' capabilities

Android phones are manufactured by different OEMs, which use different vendors to get their sensors. It is very much possible that two different Android phones have different gyroscope sensors, which will have different ranges and other properties. Before developing a universal logic based on sensors, it's important to keep in mind sensor's individual properties and capabilities, which may vary from device to device. In this section, we will explore the common methods for finding out the properties and capabilities of a sensor:

  1. We will show the sensor properties in the individual TextView on the screen. In the following code snippet, the TextViewSensor, and SensorManager variables are declared:
          public class SensorCapabilityActivity extends Activity { 
     
            private SensorManager mSensorManager; 
            private int mSensorType; 
            private Sensor mSensor; 
    ...

Understanding the sensor framework callbacks


The two most important callbacks of the sensor framework are the onSensorChanged() and onAccuracyChanged() methods. In order to write efficient sensor code, it's important to understand when these methods are called, and what processing we can do in them. These callbacks are methods of the SensorEventListnener interface, which needs to be implemented in the class where the callbacks are to be received:

onSensorChanged() is the first callback and has the following syntax:

@Override 
  public void onSensorChanged(SensorEvent event) { 
   } 

Depending on the type of reporting mode of the sensor, this method will be called, either at regular frequency (Continuous mode) or whenever there is a change in the value of the sensors from the previously reported value (On the change mode). The onSensorChanged() method provides the sensor values inside the float value[] array of the SensorEvent object. These sensor values are different from the...

Time for action - using sensors in the foreground activity


In this section, we will explore how to use sensors in the activity. This is the most basic and straightforward way of using sensors. Also, it's the most efficient way if your sensor functionality only ties to that activity:

  1. The first step is to implement our activity with the SensorEventListener interface so that our activity can receive SensorEvent through the onSensorChanged() method. The following code snippet shows the necessary import statements and the class declaration:

           import android.app.Activity; 
           import android.content.Context; 
           import android.hardware.Sensor; 
           import android.hardware.SensorEvent; 
           import android.hardware.SensorEventListener; 
           import android.hardware.SensorManager; 
           import android.os.Bundle; 
     
           public class SensorActivity extends Activity implements 
           SensorEventListener{ 
    
  2. Now, we will create the...

Time for action – listing the available sensors on a device


There are multiple sensors available on a device. In this section, we will learn how to get a list of all the available sensors. We will be populating the names of the available sensors in a list and will be displaying it on the screen using ListView.

  1. The following code block shows the declarations required by the activity. We don't need the SensorEventListener interface, as we will not be dealing with the values of the sensor. We declare ListView.ListAdapter, and SensorManager, along with the list of Sensor Objects to populate the list:

           public class SensorListActivity extends Activity 
           implements OnItemClickListener{ 
     
             private SensorManager mSensorManager; 
             private ListView mSensorListView; 
             private ListAdapter mListAdapter; 
             private List<Sensor> mSensorsList; 
    
  2. In the onCreate() method, we instantiate our SensorManager, ListView, and ListAdaptor...

Time for action – knowing individual sensors' capabilities


Android phones are manufactured by different OEMs, which use different vendors to get their sensors. It is very much possible that two different Android phones have different gyroscope sensors, which will have different ranges and other properties. Before developing a universal logic based on sensors, it's important to keep in mind sensor's individual properties and capabilities, which may vary from device to device. In this section, we will explore the common methods for finding out the properties and capabilities of a sensor:

  1. We will show the sensor properties in the individual TextView on the screen. In the following code snippet, the TextViewSensor, and SensorManager variables are declared:

          public class SensorCapabilityActivity extends Activity { 
     
            private SensorManager mSensorManager; 
            private int mSensorType; 
            private Sensor mSensor; 
            private TextView mSensorNameTextView...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • 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.

Description

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.

Who is this book 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

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 29, 2016
Length: 194 pages
Edition : 1st
Language : English
ISBN-13 : 9781785284663
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Apr 29, 2016
Length: 194 pages
Edition : 1st
Language : English
ISBN-13 : 9781785284663
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
₹4500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts
₹5000 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 9,384.97
Android Application Development Cookbook
₹3649.99
Android 6 Essentials
₹2457.99
Android Sensor Programming By Example
₹3276.99
Total 9,384.97 Stars icon
Banner background image

Table of Contents

7 Chapters
1. Sensor Fundamentals Chevron down icon Chevron up icon
2. Playing with Sensors Chevron down icon Chevron up icon
3. The Environmental Sensors – The Weather Utility App Chevron down icon Chevron up icon
4. The Light and Proximity Sensors Chevron down icon Chevron up icon
5. The Motion, Position, and Fingerprint Sensors Chevron down icon Chevron up icon
6. The Step Counter and Detector Sensors – The Pedometer App Chevron down icon Chevron up icon
7. The Google Fit Platform and APIs – The Fitness Tracker App Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(4 Ratings)
5 star 75%
4 star 25%
3 star 0%
2 star 0%
1 star 0%
Sagar Ahuja May 05, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Quite useful book with handful examples..
Amazon Verified review Amazon
Ankita Ahuja May 06, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Reached on the third chapter, so far it is pretty nice and systematic. I like the examples and full explanation of the source code, as it help beginners like me to understand and connect the pieces together.
Amazon Verified review Amazon
Akhilesh Mani May 05, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book offers a really complete coverage of the Android Sensors. I am still reading through it, and the learning curve for me is rather steep, even though I'm an experienced programmer.
Amazon Verified review Amazon
Paul in Idaho Feb 02, 2019
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This is a good book for someone who's familiar with Android programming but is just starting out with sensors. The author leaves out a few details that a beginner would have to search out. The example applications could be a little more focused.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.