android基础--采用方向传感器实现指南针

 

主界面:main.xml

<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>

为了让指南针旋转过程中保持竖屏,在manifest.xml中的activity中增加属性:

android:screenOrientation="portrait"

mainactivity.java

public class MainActivity extends Activity {

       private SensorManager sensorManager ;

       private SensorListener listener= new SensorListener();

       private ImageView imageView ;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        imageView = (ImageView) this.findViewById(R.id.imageView);

        imageView.setKeepScreenOn(true);//保持屏幕高亮,防止指南针旋转中手机屏幕锁屏

        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);//获得传感器管理服务

    }

       protected void onResume() {

              Sensor sensors = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);//得到方向传感器

              sensorManager.registerListener(listener, sensors,sensorManager.SENSOR_DELAY_GAME);//注册传感器监听

              super.onResume();

       }

    private final class SensorListener implements SensorEventListener{

           private float preDegress = 0;//用来存放上一次指南针旋转到的角度

              public void onSensorChanged(SensorEvent event) {

                     float degree = event.values[0];//数组的第一个元素存放了测量出来的方向值

                     //对imageView旋转用到动画,逆时针旋转

                     Animation animation = new RotateAnimation(preDegress, -degree,

                                                               Animation.RELATIVE_TO_SELF,0.5f, Animation.RELATIVE_TO_SELF,0.5f);

                     animation.setDuration(200);//旋转时间

                     imageView.startAnimation(animation);

                     preDegress = -degree ;//缓存本次旋转角度,以便下次旋转时候用

              }

 

              public void onAccuracyChanged(Sensor sensor, int accuracy) {

                    

              }

          

    }

}

阅读更多
个人分类: android学习
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭