传感器,分为方向,加速度(重力),光线,磁场,距离(临近性),温度等
方向传感器 Sensor.TYPE_ORIENTATION
加速度(重力)传感器 Sensor.TYPE_ACCELEROMETER
光线传感器 Sensor.TYPE_LIGHT
磁场传感器 Sensor.TYPE_MAGNETIC_FIELD
距离(临近性)传感器 Sensor.TYPE_PROXIMITY
温度传感器
Sensor.TYPE_TEMPERATURE
例子代码 指南针
0 代表北 (North)
90 代表东 (East)
180 代表南 (South)
270 代表西 (West)
上北 下南 左西 右东
xml布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/zhinanzhen"
android:id="@+id/imageView"/>
</RelativeLayout>
java代码
public class MainActivity extends Activity {
private ImageView imageView;
private SensorManager sensorManager;
private MyListener listener;
/*
* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
* 由于传感器会很耗电,所以一般不在onCreate方法里创建,一般就在onResume()里创建
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) this.findViewById(R.id.imageView);
//保持屏幕高亮,不黑屏
imageView.setKeepScreenOn(true);
//得到传感器的服务
sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
//获取传感器
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
sensorManager.registerListener(listener, sensor,SensorManager.SENSOR_DELAY_GAME);
}
private final class MyListener implements SensorEventListener{
private float degree=0;//默认是0开始
@Override
public void onSensorChanged(SensorEvent event) {
//获取方向值
float fval = event.values[0];
//现在需要旋转图片,所以需要使用 RotateAnimation
RotateAnimation animation = new RotateAnimation(degree,-fval,
Animation.RELATIVE_TO_SELF,0.5f,
Animation.RELATIVE_TO_SELF,0.5f);
animation.setDuration(200);
imageView.startAnimation(animation);
degree = -fval;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
@Override
protected void onPause() {
sensorManager.unregisterListener(listener);
super.onPause();
}
}