Learn how to use the Android Environment Sensors to detect information about the user’s environment, including ambient temperature, pressure, humidity, and light.
Tutorial Teaser
The Android system supports a range of device Sensors, some implemented in hardware and some in software. The Environment Sensors are all hardware features, providing access to information about ambient temperature, pressure, humidity, and light. These sensors return values as follows: temperature is measured in degrees Celsius, atmospheric pressure in hPa millibars, relative ambient air humidity as a percentage value, and ambient light in SI lux units. In this tutorial, we will run through the basic process for using these four main Environment Sensors. We will not be using the device temperature sensor, as it is now deprecated as of Android 4.0.
There are many possible applications for these sensors, such as barometers and thermometers. You may have come across such apps in Google Play already, but it is worth noting that they may not necessarily be implementing their functions using Environment Sensors. For example, weather apps often use location data fetched over the Web to determine environment information based on where you are.
Since these sensors are provided via users’ hardware, support does vary between devices and manufacturers. At the time of writing, very few Android smartphones or tablets support all of the Environment Sensors, but many of the more recent models support one or more of them. It is vital to carry out checks on whether the user has particular sensors and to avoid using functionality that is totally reliant on them. The only exception to this is if you ensure only users with the required hardware can download your application – you can do this using the filters for an app as listed in the Google Play store.
Step 1: Create a New Android Project
Create a new Android project in Eclipse and give it a name of your choice. Let Eclipse create a main Activity, as this is the only class we will need. For the code used in this tutorial, we are targeting Android API level 14 (Android 4.0 – Ice Cream Sandwich), but you can target a more recent version if you wish. You do not need to make any alterations to the Manifest file. Your main Activity class should have the following initial structure, with your chosen class name:
public class EnvironmentCheckerActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
We are going to implement a couple of Interfaces, so extend your opening class declaration line as follows:
public class EnvironmentCheckerActivity extends Activity implements OnClickListener, SensorEventListener {
The click listener is for user interaction and the Sensor Event Listener is for receiving data from the device sensors. Eclipse should have provided import statements for the Activity and Bundle classes, but you also need to add the following to the list:
import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast;
We will be adding code to the class later.
Step 2: Design User Interaction
In order to demonstrate the basic process for using the Environment Sensors, we are going to build a simple user interface. The app will display a list of four buttons, one for each of the sensors we will be using. When the user selects a button, the app will attempt to retrieve the appropriate information and present it within a Text View. First, let’s define some text Strings we will use within the interface. Open your “res/values/strings.xml” file and edit it to contain the following:
<resources> <string name="hello">Choose from the options to check your environment</string> <string name="app_name">Environment Checker</string> <string name="ambient_label">Ambient Temperature</string> <string name="light_label">Light</string> <string name="pressure_label">Pressure</string> <string name="humidity_label">Relative Humidity</string> <string name="text_placeholder">-</string> </resources>
These represent the title, introductory text, button labels, and a placeholder for the Text Views. We are going to use a couple of drawable resources for the design, but you can omit them if you wish. To use them, in each of your app’s drawables folders, you will need to create two additional files, “back.xml” and “btn.xml” (select each drawable folder in turn and choose “File” > “New” > “File”, then enter the file name). For the “back.xml” file, enter the following code:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:dither="true"> <gradient android:startColor="#FF000033" android:endColor="#FF000033" android:centerColor="#FF000066" android:angle="180" /> </shape>
For the “btn.xml” file, enter the following:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:dither="true"> <gradient android:startColor="#FF00CC00" android:endColor="#FF66CC66" android:angle="90" /> <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" /> <corners android:radius="2dp" /> </shape>
The back drawable is for the Activity background and the “btn” drawable is for the button backgrounds. Feel free to alter these designs in any way you wish – make sure you copy them to each drawable folder in your app.
Now open your app’s “main.xml” layout file (res/layout/main.xml). Enter a Scroll View and Linear Layout as follows:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/back"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dp" android:orientation="vertical" > </LinearLayout> </ScrollView>
Inside the Linear Layout, add the introduction, then a Button and Text View for each of the four sensors:
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="10dp" android:textColor="#FFFFFF00" android:text="@string/hello" /> <Button android:id="@+id/ambient_btn" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/ambient_label" android:background="@drawable/btn" /> <TextView android:id="@+id/ambient_text" android:paddingBottom="20dp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/text_placeholder" android:textColor="#FFFF66FF" android:textStyle="bold" /> <Button android:id="@+id/light_btn" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/light_label" android:background="@drawable/btn" /> <TextView android:id="@+id/light_text" android:paddingBottom="20dp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/text_placeholder" android:textColor="#FFFF66FF" android:textStyle="bold" /> <Button android:id="@+id/pressure_btn" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/pressure_label" android:background="@drawable/btn" /> <TextView android:id="@+id/pressure_text" android:paddingBottom="20dp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/text_placeholder" android:textColor="#FFFF66FF" android:textStyle="bold" /> <Button android:id="@+id/humidity_btn" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/humidity_label" android:background="@drawable/btn" /> <TextView android:id="@+id/humidity_text" android:paddingBottom="20dp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/text_placeholder" android:textColor="#FFFF66FF" android:textStyle="bold" />
Each Button and Text View pair is virtually identical, with ID attributes to identify them in the Java code. Of course, you can alter any of the design elements if you wish. The layout refers to the drawable resources and Strings.
Get the Full Series!
This tutorial series is available to Tuts+ Premium members only. Read a preview of this tutorial on the Tuts+ Premium web site or login to Tuts+ Premium to access the full content.
Joining Tuts+ Premium. . .
For those unfamiliar, the family of Tuts+ sites runs a premium membership service called Tuts+ Premium. For $19 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Mobiletuts+, Nettuts+, Aetuts+, Audiotuts+, Vectortuts+, and CgTuts+. You’ll learn from some of the best minds in the business. Become a premium member to access this tutorial, as well as hundreds of other advanced tutorials and screencasts.