step2:设计应用的UI界面,main.xml
复制代码 代码如下:
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
android:layout_height="wrap_content"
android:src="@drawable/compass"
android:id="@+id/imageView"
/>
step3:MainActivity.java
复制代码 代码如下:
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);//屏幕高亮
//获取系统服务(SENSOR_SERVICE)返回一个SensorManager 对象
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);
super.onResume();
}
@Override
protected void onPause() {
//应用不在前台时候销毁掉监听器
manager.unregisterListener(listener);
super.onPause();
}
private final class SensorListener implements SensorEventListener {
private float predegree = 0;
@Override
public void onSensorChanged(SensorEvent event) {
float degree = event.values[0];// 存放了方向值
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;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
}
step4:AndroidManifest.xml
复制代码 代码如下:
android:versionCode="1"
android:versionName="1.0">
android:label="@string/app_name">



