传感器:手机常用传感器有方向传感器、重力传感器、光线传感器等。
上北0度 右东90度 下南180度 左西 270度
MainActivity
Sensor.TYPE_ORIENTATION 方向传感器
Sensor.TYPE_ACCELEROMETER 重力
Sensor.TYPE_LIGHT 光线
Sensor.TYPE_MAGNETIC_FIELD 磁场
Sensor.TYPE_PROXIMITY 距离
Sensor.TYPE_TEMPERATURE 温度
采样率
SensorManager.SENSOR_DELAY_FASTEST 最快 不推荐,耗电最大,算法不好会影响ui性能
SensorManager.SENSOR_DELAY_GAME 实时性较高的游戏使用该级别
SensorManager.SENSOR_DELAY_NORMAL 标准延迟,过低对赛车有跳帧现象
SensorManager.SENSOR_DELAY_UI 用户界面,游戏不推荐,相对省电
注册监听
package cn.itcast.sensor;
import android.app.Activity;
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.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ImageView imageView;
private SensorManager manager;
private SensorListener listener = new SensorListener();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) this.findViewById(R.id.imageView);
imageView.setKeepScreenOn(true);
manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
@Override
protected void onResume() {
Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION);//方向传感器 其他一样
manager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME);//第3个参数为采样率
super.onResume();
}
@Override
protected void onPause() { //一旦离开前台则取消 因为传感器很耗电
manager.unregisterListener(listener);
super.onPause();
}
private final class SensorListener implements SensorEventListener{
private float predegree = 0;
//测量到数据后调用此方法
public void onSensorChanged(SensorEvent event) {
float degree = event.values[0];//存放了方向值 90
RotateAnimation animation = new RotateAnimation(predegree, -degree,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
animation.setDuration(200);
imageView.startAnimation(animation);
predegree = -degree;
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/zn"
android:id="@+id/imageView"
/>
</LinearLayout>