Skip to main content

Kotlin Android SensorManager Example

In the world of mobile app development, sensors play an important role in providing users with a better experience. The SensorManager in Android is a class that allows developers to access the various sensors available on a device. In this article, we will explore SensorManager in detail and provide code examples in Kotlin.

Setting up SensorManager

Before we can use SensorManager, we need to set it up. We start by creating an instance of the SensorManager class. We do this by calling the getSystemService() method and passing in the SENSOR_SERVICE constant.

val sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager

Once we have created an instance of the SensorManager class, we can use it to access the various sensors available on the device.

Accessing Sensors

The SensorManager class provides several methods for accessing sensors. The most common method is getDefaultSensor(), which returns the default sensor for a given sensor type.

val accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)

The above code gets the default accelerometer sensor on the device. We can also get a list of all available sensors using the getSensorList() method.

val sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL)

This returns a list of all the sensors available on the device.

Registering for Sensor Events

Once we have access to a sensor, we need to register for sensor events. We do this by creating an instance of the SensorEventListener interface and registering it with the SensorManager.

val sensorEventListener = object : SensorEventListener {
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
// Called when the accuracy of the sensor changes
}

override fun onSensorChanged(event: SensorEvent?) {
// Called when a sensor event occurs
}
}

sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL)

The above code registers the sensorEventListener object with the SensorManager, to receive events from the accelerometerSensor. The SENSOR_DELAY_NORMAL parameter specifies the rate at which sensor events are delivered.

Unregistering for Sensor Events

When we are done with a sensor, we need to unregister the SensorEventListener. This is done using the unregisterListener() method of the SensorManager class.

sensorManager.unregisterListener(sensorEventListener)

More Examples

In this section you will learn about SensorManager via simple step by step examples.

Example 1: SensorManager

A simple SensorManager example.

Step 1: Create Project

  1. Open your Android Studio IDE.
  2. In the menu go to File --> Create New Project.
  3. Choose Empty Project template.

Step 2: Add Dependencies

No special dependencies are needed for this project.

Step 3: Design Layouts

Go to your res/layout directory so as to design your user interface.

We will have 2 layouts:

  1. activity_main.xml
  2. list_item.xml

First create a file known as activity_main.xml and add the following code:

(a). activity_main.xml

This is our MainActivity's layout. Our root element will be a LinearLayout. Inside it we will place a TextView and ListView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

<TextView
android:id="@+id/sensors"
android:text="@string/sensors"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Display1"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">

</ListView>

</LinearLayout>

Next create a list_item.xml file and add the following code:

(b). list_item.xml

This will represent a single item in our ListView. Add two TextViews:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello!"
android:id="@+id/title"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold"
android:padding="@dimen/_10dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hello!"
android:id="@+id/sensordata"
app:layout_constraintTop_toBottomOf="@id/title"
android:padding="@dimen/_10dp"/>
</android.support.constraint.ConstraintLayout>

Step 4 : Create Adapter

Next create a file known as ListAdapter.java and add the following code:

import android.content.Context;
import android.hardware.Sensor;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;

Then extend the ArrayAdapter from the android.widget package:

public class ListAdapter extends ArrayAdapter {

Then define the following instance fields:


private Context mContext;
private List<Sensor> mSensors;

Receive them via the constructor:

    public ListAdapter(@NonNull Context context, int resource, List<Sensor> mSensors) {
super(context, resource,mSensors);
mContext=context;
this.mSensors = mSensors;
}

Override the getView function:

    @NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater layoutInflater=(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v=layoutInflater.inflate(R.layout.list_item,null,false);
TextView title=v.findViewById(R.id.title);
title.setText(mSensors.get(position).getName());
TextView sensorId=v.findViewById(R.id.sensordata);
sensorId.setText(mSensors.get(position).getVendor());
Log.d("sdlc",mSensors.get(position).toString());

Log.d("sdlc","adapter");
return v;


}
}

Here is the full code:

ListAdapter.java

package com.example.volansys.sensormanager;

import android.content.Context;
import android.hardware.Sensor;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

public class ListAdapter extends ArrayAdapter {


private Context mContext;
private List<Sensor> mSensors;
public ListAdapter(@NonNull Context context, int resource, List<Sensor> mSensors) {
super(context, resource,mSensors);
mContext=context;
this.mSensors = mSensors;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater layoutInflater=(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v=layoutInflater.inflate(R.layout.list_item,null,false);
TextView title=v.findViewById(R.id.title);
title.setText(mSensors.get(position).getName());
TextView sensorId=v.findViewById(R.id.sensordata);
sensorId.setText(mSensors.get(position).getVendor());
Log.d("sdlc",mSensors.get(position).toString());

Log.d("sdlc","adapter");
return v;


}
}

Step 5: Create MainActivity

Next create a file known as MainActivity.java and add the following code:

    import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.EventListener;
import java.util.List;

Extend the AppCompatActivity and implement the SensorEventListener:

    public class MainActivity extends AppCompatActivity implements SensorEventListener {

Declare a SensorManager, Sensor object, a string, a List of Sensor objects and an AlertDialog.Builder object as shown below:

        private SensorManager mSensorManager;
private Sensor mSensor;
private String data;
List<Sensor> mSensorList;
private AlertDialog.Builder mAlertDialog;

Override the onCreate with the following code:

        @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAlertDialog= new AlertDialog.Builder(MainActivity.this);
mSensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
mSensorList=mSensorManager.getSensorList(Sensor.TYPE_ALL);
Log.d("sdlc","count:"+mSensorList.size());
Log.d("sdlc","mainactivity");
ListView listView=findViewById(R.id.list);
ListAdapter listAdapter=new ListAdapter(this,R.layout.list_item,mSensorList);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mSensor=mSensorManager.getDefaultSensor(mSensorList.get(position).getType());
mAlertDialog.setTitle(mSensorList.get(position).getName());
mAlertDialog.create().show();

}
});
}

Override the other activity callback methods as shown below:


@Override
protected void onResume() {
super.onResume();
for(Sensor s:mSensorList)
mSensorManager.registerListener(this,s,SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
protected void onPause() {
super.onPause();
for(Sensor s:mSensorList)
mSensorManager.unregisterListener(this);
}

@Override
public void onSensorChanged(SensorEvent event) {
data="";
int i=0;
while (i<event.values.length){
data=data+"\n"+event.values[i];
i++;
}
mAlertDialog.setMessage(data);
Log.d("sdlc",data);

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}

Here is the full code:

MainActivity.java

    package com.example.volansys.sensormanager;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.EventListener;
import java.util.List;

public class MainActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mSensor;
private String data;
List<Sensor> mSensorList;
private AlertDialog.Builder mAlertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAlertDialog= new AlertDialog.Builder(MainActivity.this);
mSensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
mSensorList=mSensorManager.getSensorList(Sensor.TYPE_ALL);
Log.d("sdlc","count:"+mSensorList.size());
Log.d("sdlc","mainactivity");
ListView listView=findViewById(R.id.list);
ListAdapter listAdapter=new ListAdapter(this,R.layout.list_item,mSensorList);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mSensor=mSensorManager.getDefaultSensor(mSensorList.get(position).getType());
mAlertDialog.setTitle(mSensorList.get(position).getName());
mAlertDialog.create().show();

}
});
}


@Override
protected void onResume() {
super.onResume();
for(Sensor s:mSensorList)
mSensorManager.registerListener(this,s,SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
protected void onPause() {
super.onPause();
for(Sensor s:mSensorList)
mSensorManager.unregisterListener(this);
}

@Override
public void onSensorChanged(SensorEvent event) {
data="";
int i=0;
while (i<event.values.length){
data=data+"\n"+event.values[i];
i++;
}
mAlertDialog.setMessage(data);
Log.d("sdlc",data);

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

NumberLink
1.Download Example
2.Follow code author
3.Code: Apache 2.0 License

Conclusion

In conclusion, SensorManager is an important class in Android that allows developers to access the various sensors available on a device. In this article, we have explored how to set up SensorManager, access sensors, register for sensor events, and unregister for sensor events. By following the steps outlined in this article, you can start using SensorManager in your Android app.