package com.jared.emsensorsstudy;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
public class MagneticSensor extends AppCompatActivity {
private SensorManager sensorManager;
private ImageView compassImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_magnetic_sensor);
compassImage = (ImageView)findViewById(R.id.compass_img);
initWithCompass();
}
@Override
protected void onDestroy() {
super.onDestroy();
sensorManager.unregisterListener(listener);
}
private void initWithCompass() {
sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
Sensor magneticSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
Sensor acclerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(listener, magneticSensor, SensorManager.SENSOR_DELAY_GAME);
sensorManager.registerListener(listener, acclerSensor, SensorManager.SENSOR_DELAY_GAME);
}
private SensorEventListener listener = new SensorEventListener() {
float[] acclerValues = new float[3];
float[] magneticValues = new float[3];
private float lastRotateDegree;
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
switch (sensorEvent.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
acclerValues = sensorEvent.values.clone();
break;
case Sensor.TYPE_MAGNETIC_FIELD:
magneticValues = sensorEvent.values.clone();
break;
default:
break;
}
float[] values = new float[3];
float[] R = new float[9];
//调用getRotaionMatrix获得变换矩阵R[]
SensorManager.getRotationMatrix(R, null, acclerValues, magneticValues);
SensorManager.getOrientation(R, values);
//经过SensorManager.getOrientation(R, values);得到的values值为弧度
//转换为角度
float rotateDegree = -(float)Math.toDegrees(values[0]);
if(Math.abs(rotateDegree - lastRotateDegree) > 2) {
RotateAnimation animation = new RotateAnimation(
lastRotateDegree, rotateDegree, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
animation.setFillAfter(true);
compassImage.startAnimation(animation);
lastRotateDegree = rotateDegree;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
}
这里通过加速度和磁传感器来实现一个方向,由于方向传感器官方已经不提倡使用了。执行效果例如以下:
传感器就先学习这些了。
附:參考《第一行代码》