Android Light Sensor – Environment Sensors

In this android tutorial, we are going to learn how to get information about our android device light sensor.

According to Google’s developer’s guide – The Android platform provides four sensors that let you monitor various environmental properties. You can use these sensors to monitor relative ambient humidity, illuminance, ambient pressure, and ambient temperature near an Android-powered device. All four environment sensors are hardware-based and are available only if a device manufacturer has built them into a device. With the exception of the light sensor, which most device manufacturers use to control screen brightness, environment sensors are not always available on devices. Because of this, it’s particularly important that you verify at runtime whether an environment sensor exists before you attempt to acquire data from it.

We are going to use a ListView control to display the information we will obtain from android light sensor.

Before we dive into more details, it is important for us to understand what we are planning to achieve. Below is the screen-shot of the application we will be creating.

android light sensors

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidLightSensor

Package: com.inducesmile.androidlightsensor

Select Blank Activity

Name the Activity LightSensorActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

Lets start with our project.

Go to the res folder, then double click on the values folder and double click on the colors.xml file and add the following lines of codes. This will holder all the colors we will use in this tutorial.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

Now, head over to the strings.xml file and modify the content with the code below.

<resources>
    <string name="app_name">Android Light Sensor</string>
</resources>

We are going to use android CardView widget to the ListView items. In order to work CardView, we are going to add CardView as a dependencies in our android project.

Our app build.gradle file content is updated with a single line of code.

apply plugin: 'com.android.application'
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"
    defaultConfig {
        applicationId "com.inducesmile.androidlightsensor"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:cardview-v7:23.0.+'
}

Update Manifest.xml file content as shown.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.inducesmile.androidlightsensor">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".LightSensorActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

We are going to create the main layout of our android app. Open the file activity_light_sensor.xml, copy and paste the code below inside the file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.inducesmile.androidlightsensor.LightSensorActivity">
    <ListView
        android:id="@+id/light_sensor"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_margin="8dp"
        android:listSelector="@android:color/transparent"
        android:scrollbars="none" />
</RelativeLayout>

For the Activity file, open LightSensorActivity file, we will get the instance of the ListView widget in the layout file.

We will add the Sensor and SensorManager classes as variable in the Activity class.

private SensorManager sensorManager;
private Sensor lightSensor;

Inside the onCreate(Bundle savedInstanceState) method of the Activity class, we will create the objects of the Sensor and SensorManager classes.

sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

We will go on to register the Sensor object in the onResume() and unregister the Sensor object in the onPause() method of the Activity class.

In the onSensorChanged(SensorEvent event), we will get the Light Sensor data, wrap it in an Entity object and store it in a List Object.

The data will be as one of the parameters of the Adapter class. Open LightSensorActivity class, copy and paste the code inside the file.

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class LightSensorActivity extends AppCompatActivity implements SensorEventListener {
    private SensorManager sensorManager;
    private Sensor lightSensor;
    private String lightSensorReading;
    private String name = "";
    private String vendor;
    private String version;
    private String maxRange;
    private String minRange;
    private String resolution;
    private String power;
    private HardwareAdapter hardwareAdapter;
    private ListView lightSensorListView;
    private List<HardwareObject> lSensor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_light_sensor);
        sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        //name = (String.valueOf(lightSensor.getName()).equals(""))? String.valueOf(lightSensor.getName()) : "";
        System.out.println("Sensor Name " + lightSensor.getName());
        name = lightSensor.getName();
        vendor = String.valueOf(lightSensor.getVendor());
        version = String.valueOf(lightSensor.getVersion());
        maxRange = String.valueOf(lightSensor.getMaximumRange());
        minRange = String.valueOf(lightSensor.getMinDelay());
        resolution = String.valueOf(lightSensor.getResolution());
        power = String.valueOf(lightSensor.getPower());
        if(lightSensor != null){
            sensorManager.registerListener(this, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }
    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }
    @Override
    public void onSensorChanged(SensorEvent event) {
        if(event.sensor.getType() == Sensor.TYPE_LIGHT){
            lightSensorReading = String.valueOf(event.values[0]);
            lSensor = new ArrayList<HardwareObject>();
            lSensor.add(new HardwareObject("Light Sensor Reading", lightSensorReading));
            lSensor.add(new HardwareObject("Name", name));
            lSensor.add(new HardwareObject("Vendor", vendor));
            lSensor.add(new HardwareObject("Version", version));
            lSensor.add(new HardwareObject("Max Range", maxRange));
            lSensor.add(new HardwareObject("Min Delay", minRange));
            lSensor.add(new HardwareObject("Resolution", resolution));
            lSensor.add(new HardwareObject("Power", power));
            hardwareAdapter = new HardwareAdapter(LightSensorActivity.this, lSensor);
            lightSensorListView = (ListView)findViewById(R.id.light_sensor);
            lightSensorListView.setAdapter(hardwareAdapter);
        }
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
}

Now, we will create the simple Entity object that is use to wrap our individual date and late on it is stored in List object.

Create a java file in the application package folder and name it HardwareObject.java. Open this file in your IDE and paste the following code.

public class HardwareObject {
    private String hardware;
    private String hardwareMeaning;
    public HardwareObject(String hardware, String hardwareMeaning) {
        this.hardware = hardware;
        this.hardwareMeaning = hardwareMeaning;
    }
    public String getHardware() {
        return hardware;
    }
    public String getHardwareMeaning() {
        return hardwareMeaning;
    }
}

The List Adapter class will inflate a layout file that contains the View components of the List items. Right on the layout folder, create a new layout file and name it hardware_cardview.xml.

Open the layout file and add this code inside the file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:elevation="8dp"
    android:layout_marginBottom="8dp"
    card_view:cardUseCompatPadding="true">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp">
        <TextView
            android:id="@+id/header"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:textColor="@color/colorPrimary"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"/>
        <TextView
            android:id="@+id/header_value"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:layout_alignTop="@+id/header"
            android:textColor="@color/colorPrimary"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </RelativeLayout>
</android.support.v7.widget.CardView>

Finally, we will create an Adapter class for the List widget. The class will inherit from the BaseAdapter default class. We are going to ovverride the getView(int position, View convertView, ViewGroup parent) method of the Adapter class and few other methods.

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class HardwareAdapter extends BaseAdapter {
    private LayoutInflater layoutInflater;
    private List<HardwareObject> listStorage;
    public HardwareAdapter(Context context, List<HardwareObject> customizedListView) {
        layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        listStorage = customizedListView;
    }
    @Override
    public int getCount() {
        return listStorage.size();
    }
    @Override
    public Object getItem(int position) {
        return position;
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder listViewHolder;
        if(convertView == null){
            listViewHolder = new ViewHolder();
            convertView = layoutInflater.inflate(R.layout.hardware_cardview, parent, false);
            listViewHolder.hardware = (TextView)convertView.findViewById(R.id.header);
            listViewHolder.hardwareMeaning = (TextView)convertView.findViewById(R.id.header_value);
            convertView.setTag(listViewHolder);
        }else{
            listViewHolder = (ViewHolder)convertView.getTag();
        }
        listViewHolder.hardware.setText(listStorage.get(position).getHardware());
        listViewHolder.hardwareMeaning.setText(listStorage.get(position).getHardwareMeaning());
        return convertView;
    }
    static class ViewHolder{
        TextView hardware;
        TextView hardwareMeaning;
    }
}

This brings us to the end of this tutorial. I hope that you have learn something.

I have a complete Android login source codes with advance features and admin back-end with user login details that comprises of Android Facebook Login, Android Twitter Login, Android Google Plus Login, Android Login and Registration with Php and MySql, Android Login with Firebase. It sells for $3.

Kindly contact me if you need it. I offer 24 – 7 support for smooth integration in your application.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email address so that you will be among the first to receive my new post once it is published.

Please if you love this tutorial, kindly download my android app – Complete Mathematics – in Google Play Store and let me know what you think about it.

One Response

Add a Comment