我大一时候买的安卓手机共有三个传感器,分别是:
3-AXIS ACCELEROMETER (三轴加速度计)
Proximity Sensor (接近度传感器)
Light Sensor (光线传感器)
在程序中使用的方法如下:
package com.example.test;
import java.util.List;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
<span style="white-space:pre"> </span>private SensorManager sm;
private mylistener ml;
protected void onCreate(Bundle savedInstanceState) {
sm = (SensorManager)getSystemService(SENSOR_SERVICE);
List<Sensor> kkk = sm.getSensorList(Sensor.TYPE_ALL);
ml = new mylistener();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView c = (TextView)(findViewById(R.id.view));
String s = "";
for (int i = 0;i < kkk.size();++i)
s += kkk.get(i).getName() + '\n';
c.setText(s);
}
@Override
protected void onResume() {
Sensor sensor_orientation=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(ml,sensor_orientation, SensorManager.SENSOR_DELAY_NORMAL);
super.onResume();
}
@Override
protected void onPause() {
sm.unregisterListener(ml);
super.onPause();
}
private final class mylistener implements SensorEventListener {
@Override
public void onSensorChanged(SensorEvent event) {
TextView cc = (TextView)(findViewById(R.id.view2));
// TODO Auto-generated method stub
if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
cc.setText("x: "+x+"\ny: "+y+"\nz: "+z);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
}
运行结果是显示所有的传感器名称,并显示加速度三个方向的分量。