Android如何应用电子罗盘(指南针)方向传感器?
发布时间:2021-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(R.layout.compass);
imageView=(ImageView)findViewById(R.id.compass_imageView);
//传感器管理器
SensorManagersm=(SensorManager)getSystemService(SENSOR_SERVICE);
//注册传感器(Sensor.TYPE_ORIENTATION(方向传感器);SENSOR_DELAY_FASTEST(0m秒延迟);
//SENSOR_DELAY_GAME(20000毫秒延迟),SENSOR_DELAY_UI(60000毫秒延迟)
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本文分享了如何实现电子罗盘(指南针)方向传感器的应用。我希望以上内容能对您有所帮助,让您学习更多的知识。如果你认为这篇文章很好,你可以分享它,让更多的人看到它!