光线传感器:
public class MainActivity extends Activity {
private SensorManager mSensorManager;
private MyListener listener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new MyListener();
//获取传感器的服务
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
//得到光线传感器
Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
mSensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
private class MyListener implements SensorEventListener{
//当精确度变化的时候调用的方法
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
//当传感器发现数据变化的时候调用的方法
@Override
public void onSensorChanged(SensorEvent event) {
float light = event.values[0];//x方向
System.out.println("当前光线强度:"+light);
}
}
@Override
protected void onDestroy() {
mSensorManager.unregisterListener(listener);
listener = null;
super.onDestroy();
}
}
方向传感器:
public class MainActivity extends Activity {
private SensorManager mSensorManager;
private MyListener listener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new MyListener();
//获取传感器的服务
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
//得到方向传感器
Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
mSensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
private class MyListener implements SensorEventListener{
//当精确度变化的时候调用的方法
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
//当传感器发现数据变化的时候调用的方法
@Override
public void onSensorChanged(SensorEvent event) {
//0=North, 90=East, 180=South, 270=West
float angle = event.values[0];
System.out.println("angle:"+angle);
}
}
@Override
protected void onDestroy() {
mSensorManager.unregisterListener(listener);
listener = null;
super.onDestroy();
}
}