xml布局代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btnGetSensor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btngetsensorstr"/>
</LinearLayout>
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<Sensor> 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);
}
}