光线传感器 + 传感器指南针

时间:2022-09-04 09:11:44

1.传感器指南针配合图片动画

光线传感器:

public class MainActivity extends Activity {
private SensorManager sm; //传感器服务
private MyListener listener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
//光线传感器
Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_LIGHT);//翻回各种传感器
listener = new MyListener();
sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);//注册一个监听器,监听sensor;最后一个参数:采样频率
}

private class MyListener implements SensorEventListener{
@Override
public void onSensorChanged(SensorEvent event) {//当传感器数值放生变化
float light = event.values[0]; //光线强弱
System.out.println("light:"+light);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}
@Override
protected void onDestroy() { //关掉监听器
sm.unregisterListener(listener);
listener = null;
super.onDestroy();
}

}


传感器指南针:

public class MainActivity extends Activity {
private SensorManager sm;
private MyListener listener;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
iv = (ImageView) findViewById(R.id.iv);
//方向传感器
Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
listener = new MyListener();
sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME);
}

private class MyListener implements SensorEventListener{
float lastangle = 0;
@Override
public void onSensorChanged(SensorEvent event) {
// 0=North, 90=East, 180=South, 270=West
float angle = event.values[0];//手机与正北方向的夹角
System.out.println("angle:"+angle);
RotateAnimation ra = new RotateAnimation(-lastangle, angle,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
iv.startAnimation(ra);
lastangle = angle;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}
@Override
protected void onDestroy() {
sm.unregisterListener(listener);
listener = null;
super.onDestroy();
}

}