欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-08-27 13:41:46
简介 现在每部android手机里边都会内置有许多传感器,如光照传感器、加速度传感器、地磁传感器、压力传感器、温度传感器等,它们能够监测到各种发生在手机撒花姑娘的物理事件...

简介

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

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

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

main.xml

<?xml version="1.0" encoding="utf-8"?> 
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  android:orientation="vertical"  
  android:gravity="center" 
  > 
  <imageview 
    android:id="@+id/compass_imageview" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@drawable/compass" /> 
</linearlayout> 

mainactivity.java

import android.app.activity; 
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 compassactivity extends activity implements sensoreventlistener { 
  private imageview imageview; 
  private float currentdegree = 0f; 
  public void oncreate(bundle savedinstancestate) { 
    super.oncreate(savedinstancestate); 
    setcontentview(r.layout.compass); 
    imageview = (imageview) findviewbyid(r.id.compass_imageview); 
    // 传感器管理器 
    sensormanager sm = (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); 
  } 
  //传感器报告新的值(方向改变) 
  public void onsensorchanged(sensorevent event) { 
    if (event.sensor.gettype() == sensor.type_orientation) { 
      float degree = 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坐标的伸缩值 
      */ 
      rotateanimation ra = new rotateanimation(currentdegree, -degree, 
          animation.relative_to_self, 0.5f, 
          animation.relative_to_self, 0.5f); 
      //旋转过程持续时间 
      ra.setduration(200); 
      //罗盘图片使用旋转动画 
      imageview.startanimation(ra); 
      currentdegree = -degree; 
    } 
  } 
  //传感器精度的改变 
  public void onaccuracychanged(sensor sensor, int accuracy) { 
  } 
} 

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接