Thursday, 22 November 2012

Show the list of Available Sensors in Android

In Android we can find sensor list by using (android.hardware.SensorManager) class.

Steps:

1) Get SensorManager object

SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

2) SensorManager provide a method getSensorList() method

using above method with parameter Sensor.TYPE_ALL to get all the sensors

Below code shows listofSensors

List<Sensor> listofSensors = sensorManager.getSensorList(Sensor.TYPE_ALL);

Output Screenshot:




















Android Activity(MainActivity.java)

package com.androidsurya.androidsensorlist;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SensorManager sensorManager = (SensorManager)                                    getSystemService(Context.SENSOR_SERVICE);
List<Sensor> listofSensors = sensorManager.getSensorList(Sensor.TYPE_ALL);

List<String> listSensorTypes = new ArrayList<String>();
for (int i = 0; i < listofSensors.size(); i++) {
listSensorTypes.add(listofSensors.get(i).getName());
}

setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listSensorTypes));
getListView().setTextFilterEnabled(true);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

Register Activity in Android Manifest file

 <activity
            android:name="com.androidsurya.androidsensorlist.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>




No comments:

Post a Comment

Android SQLite Database Viewer or Debuging with Stetho

Every Android Developer uses SQLite Database to store data into the Android Application data. But to view the data in SQLite have a lot of...