Android获取手机中的传感器

xml布局代码:


android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

android:id="@+id/btnGetSensor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btngetsensorstr"/>

activity代码:
package com.nine.sensordemo;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

private Button btnGetSensor;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    initWedget();
}

private void initWedget() {
     btnGetSensor = (Button) findViewById(R.id.btnGetSensor);
     btnGetSensor.setOnClickListener(this);
}

public void onClick(View v) {
    SensorManager manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    //得到手机上所有的传感器
    List listSensor = manager.getSensorList(Sensor.TYPE_ALL);
    int i = 1;
    for (Sensor sensor : listSensor) {
        Log.d("sensor " + i, sensor.getName());
        i++;
    }
    //通过调用getDefaultSensor方法获取某一个类型的默认传感器
    //Sensor s = manager.getDefaultSensor(Sensor.TYPE_LIGHT);
}

}

你可能感兴趣的:(Android获取手机中的传感器)