设为首页 加入收藏

TOP

Android 利用方向传感器实现 指南针
2014-11-24 03:32:24 来源: 作者: 【 】 浏览:2
Tags:Android 利用 方向 传感器 实现 指南针

step1:新建一个项目Compass,并将一张指南针图片导入到res/drawable-hdpi目录中


1365944950_9473.jpg


step2:设计应用的UI界面,main.xml


step3:MainActivity.java


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 {


private ImageView imageView;


/** 传感器管理器 */
private SensorManager manager;


private SensorListener listener = new SensorListener();


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


imageView = (ImageView) this.findViewById(R.id.imageView);
imageView.setKeepScreenOn(true);//屏幕高亮
//获取系统服务(SENSOR_SERVICE)返回一个SensorManager 对象
manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}


@Override
protected void onResume() {
/**
* 获取方向传感器
* 通过SensorManager对象获取相应的Sensor类型的对象
*/
Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
//应用在前台时候注册监听器
manager.registerListener(listener, sensor,
SensorManager.SENSOR_DELAY_GAME);
super.onResume();
}


@Override
protected void onPause() {
//应用不在前台时候销毁掉监听器
manager.unregisterListener(listener);
super.onPause();
}


private final class SensorListener implements SensorEventListener {


private float predegree = 0;


@Override
public void onSensorChanged(SensorEvent event) {
/**
* values[0]: x-axis 方向加速度
   values[1]: y-axis 方向加速度
   values[2]: z-axis 方向加速度
*/
float degree = event.values[0];// 存放了方向值
/**动画效果*/
RotateAnimation animation = new RotateAnimation(predegree, degree,
Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
animation.setDuration(200);
imageView.startAnimation(animation);
predegree=-degree;

/**
float x=event.values[SensorManager.DATA_X];
float y=event.values[SensorManager.DATA_Y];
float z=event.values[SensorManager.DATA_Z];
Log.i("XYZ", "x="+(int)x+",y="+(int)y+",z="+(int)z);
*/
}


@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {


}


}
}


step4:AndroidManifest.xml


< xml version="1.0" encoding="utf-8" >
package="cn.roco.sensor"
android:versionCode="1"
android:versionName="1.0">



android:label="@string/app_name">







】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android 利用方向传感器获得手机.. 下一篇Linux 与 Windows 对UNICODE 的处..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·工业机器人TCP校准中 (2025-12-25 05:19:17)
·opc 通讯协议与 TCP (2025-12-25 05:19:15)
·labview中tcp/ip通信 (2025-12-25 05:19:13)
·新书介绍《Python数 (2025-12-25 04:49:47)
·怎么利用 Python 进 (2025-12-25 04:49:45)