马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这里需要说明的是,如果手机上有支持方向传感器的硬件的话,应该可以,如果没有,此功能就不能实现:此功能基本上实现了一个指南针的效果
1.布局文件的配置:<LinearLayout 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:gravity="center"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/south"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/compass"
/>
</LinearLayout>
2.activity程序功能的实现:package com.example.compass_test;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ImageView iv;
private SensorManager sensorManager;
private Sensor sensor;
private MySensorEventListener listener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.iv = (ImageView) this.findViewById(R.id.south);
this.iv.setKeepScreenOn(true); //保持屏幕的高亮
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
listener = new MySensorEventListener();
//获取传感器的管理者
sensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
//方向传感器
sensor = this.sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
//注册监听
sensorManager.registerListener(listener, sensor,SensorManager.SENSOR_DELAY_GAME);
super.onResume();
}
private class MySensorEventListener implements SensorEventListener
{
float predergee = 0;
//当传感器的精度变化时
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
//当传感器发生改变的时候
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
float[] values = event.values;
float degree = values[0]; //表示正北方向夹角的度数
System.out.println("与长辈方向的夹角: " + degree);
/**
* RotateAnimation 是旋转动画:
* 参数:
* predergee:旋转的开始角度
* -degree:旋转的结束角度
* Animation.RELATIVE_TO_SELF X轴的伸缩模式
* 0.5f X轴的伸缩值
* Animation.RELATIVE_TO_SELF Y轴的伸缩模式
* 0.5f Y轴的伸缩值
*/
RotateAnimation rotateAnimation = new RotateAnimation(predergee,
-degree,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
rotateAnimation.setDuration(200); //设置动画的持续时间
iv.startAnimation(rotateAnimation); //开始时间
predergee = -degree;
}
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
sensorManager.unregisterListener(listener);
super.onStop();
}
}
|