失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > android方向传感器 指南针 Android如何实现电子罗盘(指南针)方向传感器的应用

android方向传感器 指南针 Android如何实现电子罗盘(指南针)方向传感器的应用

时间:2019-07-31 20:40:04

相关推荐

android方向传感器 指南针 Android如何实现电子罗盘(指南针)方向传感器的应用

Android如何实现电子罗盘(指南针)方向传感器的应用

发布时间:-04-16 10:12:13

来源:亿速云

阅读:71

作者:小新

这篇文章给大家分享的是有关Android如何实现电子罗盘(指南针)方向传感器的应用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

简介

现在每部Android手机里边都会内置有许多传感器,如光照传感器、加速度传感器、地磁传感器、压力传感器、温度传感器等,它们能够监测到各种发生在手机撒花姑娘的物理事件。当然Android系统只是负责将这些传感器所输出的信息传递给我们,然后我们可以利用这些信息去开发一些好玩的应用。

图片神马的在网上搜个指南针图片就好了,方便学习

main.xml<?xml version="1.0"encoding="utf-8"?>

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:gravity="center"

>

android:id="@+id/compass_imageView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:src="@drawable/compass"/>

MainActivity.javaimportandroid.app.Activity;

importandroid.hardware.Sensor;

importandroid.hardware.SensorEvent;

importandroid.hardware.SensorEventListener;

importandroid.hardware.SensorManager;

importandroid.os.Bundle;

importandroid.view.animation.Animation;

importandroid.view.animation.RotateAnimation;

importandroid.widget.ImageView;

/**

*电子罗盘方向传感器

*/

publicclassComPassActivityextendsActivityimplementsSensorEventListener{

privateImageViewimageView;

privatefloatcurrentDegree=0f;

publicvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

setContentView(pass);

imageView=(ImageView)findViewById(pass_imageView);

//传感器管理器

SensorManagersm=(SensorManager)getSystemService(SENSOR_SERVICE);

//注册传感器(Sensor.TYPE_ORIENTATION(方向传感器);SENSOR_DELAY_FASTEST(0毫秒延迟);

//SENSOR_DELAY_GAME(20,000毫秒延迟)、SENSOR_DELAY_UI(60,000毫秒延迟))

sm.registerListener(ComPassActivity.this,

sm.getDefaultSensor(Sensor.TYPE_ORIENTATION),

SensorManager.SENSOR_DELAY_FASTEST);

}

//传感器报告新的值(方向改变)

publicvoidonSensorChanged(SensorEventevent){

if(event.sensor.getType()==Sensor.TYPE_ORIENTATION){

floatdegree=event.values[0];

/*

RotateAnimation类:旋转变化动画类

参数说明:

fromDegrees:旋转的开始角度。

toDegrees:旋转的结束角度。

pivotXType:X轴的伸缩模式,可以取值为ABSOLUTE、RELATIVE_TO_SELF、RELATIVE_TO_PARENT。

pivotXValue:X坐标的伸缩值。

pivotYType:Y轴的伸缩模式,可以取值为ABSOLUTE、RELATIVE_TO_SELF、RELATIVE_TO_PARENT。

pivotYValue:Y坐标的伸缩值

*/

RotateAnimationra=newRotateAnimation(currentDegree,-degree,

Animation.RELATIVE_TO_SELF,0.5f,

Animation.RELATIVE_TO_SELF,0.5f);

//旋转过程持续时间

ra.setDuration(200);

//罗盘图片使用旋转动画

imageView.startAnimation(ra);

currentDegree=-degree;

}

}

//传感器精度的改变

publicvoidonAccuracyChanged(Sensorsensor,intaccuracy){

}

}

感谢各位的阅读!关于“Android如何实现电子罗盘(指南针)方向传感器的应用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

如果觉得《android方向传感器 指南针 Android如何实现电子罗盘(指南针)方向传感器的应用》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。