Android方向传感器学习之指南针示例

刚刚跟着视频学习了关于Android中传感器的操作示例,利用方向传感器做了一个很简单的指南针应用。。。平时工作项目中很少有用到传感器功能,所以很多都不知道,现在自学些,当作慢慢入门吧。。。

首先贴出软件最终运行效果图


里面用到的这张图片素材,是临时用PPT做的一个,很简陋,能用就行了吧,这不是重点。

下面开始码代码了。。。

布局文件main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@android:color/white"
    android:gravity="center" >
    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/img" />

</LinearLayout>
很简单,里面只有一个ImageView控件

MainaActivity类

package com.and.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 {
	ImageView imgView;
	SensorManager manager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		imgView = (ImageView) findViewById(R.id.img);
		imgView.setKeepScreenOn(true);
		manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
	}

	@Override
	protected void onResume() {
		Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
		manager.registerListener(sensorListener, sensor,
				SensorManager.SENSOR_DELAY_GAME);
		super.onResume();
	}

	SensorEventListener sensorListener = new SensorEventListener() {

		private float predegree = 0;

		public void onSensorChanged(SensorEvent event) {
			float degree = event.values[0];// 数组中的第一个数是方向值
			RotateAnimation anim = new RotateAnimation(predegree, -degree,
					Animation.RELATIVE_TO_SELF, 0.5f,
					Animation.RELATIVE_TO_SELF, 0.5f);
			anim.setDuration(200);
//			imgView.setAnimation(anim);//这句错误
			imgView.startAnimation(anim);
			predegree = -degree;//记录这一次的起始角度作为下次旋转的初始角度
		}

		public void onAccuracyChanged(Sensor sensor, int accuracy) {

		}
	};

	@Override
	protected void onPause() {
		super.onPause();
		manager.unregisterListener(sensorListener);
	}
}
注意里面这一句

RotateAnimation anim = new RotateAnimation(predegree, -degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

前面两个参数,第一个是旋转的初始角度,第二个要旋转到的角度,因为这里方向传感器判断的是与手机顶部的夹角。试想,如果夹角为90度,起始“北”指向顶部,90度的话,图片需要逆时针旋转90度,所以第二个参数是负的。至于为什么要逆时针转而不是顺时针,这点我也还没有明白。请大神赐教


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值