Sensor List Example

This example shows how to access the sensors present on a device and list them.

A screenshot of the application.

We begin by declaring a unique namespace for the package we are creating. This is typically based on the reversed form of a domain name and should be unique to this package.

__package__ = "com.example.sensorlist"

We import the classes and modules needed by our application. The most relevant ones for this example are the Sensor and SensorManager classes.

from android.app import Activity
from android.content import Context
from android.hardware import Sensor, SensorManager
import android.os
from android.view import ViewGroup
from android.widget import LinearLayout, TextView

The SensorListActivity is derived from the standard Activity class and represents the application. Android will create an instance of this class when the user runs it.

class SensorListActivity(Activity):

    def __init__(self):
    
        Activity.__init__(self)

The initialisation method only needs to call the corresponding method in the base class.

The onCreate method is called when the activity is created. Our implementation calls the onCreate method of the base class, queries the available sensors and displays them in a graphical layout.

    @args(void, [android.os.Bundle])
    def onCreate(self, bundle):
    
        Activity.onCreate(self, bundle)

Information about the available sensors is obtained from the device's sensor service. This is obtained using the getSystemService method. The instance we obtain from this method needs to be cast to a suitable type so that we can access its methods.

        service = self.getSystemService(Context.SENSOR_SERVICE)
        sensorManager = CAST(service, SensorManager)

We create a vertical layout in which to place text labels for each of the sensors on the device.

        layout = LinearLayout(self)
        layout.setLayoutParams(ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT))
        layout.setOrientation(LinearLayout.VERTICAL)

A list of sensors is obtained by calling the appropriate method of the sensor manager with a constant that requests information about all of the available sensors. We iterate over this list, creating text views for each sensor that show its name.

        sensors = sensorManager.getSensorList(Sensor.TYPE_ALL)
        i = 0
        
        while i < len(sensors):
            view = TextView(self)
            view.setText(sensors[i].getName())
            layout.addView(view)
            i += 1

Finally, we use the layout as the main view in the activity.

        self.setContentView(layout)

Files