栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android 利用方向传感器实现指南针具体步骤

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android 利用方向传感器实现指南针具体步骤

step1:新建一个项目Compass,并将一张指南针图片导入到res/drawable-hdpi目录中
 
step2:设计应用的UI界面,main.xml
复制代码 代码如下:

android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/compass"
android:id="@+id/imageView"
/>


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() {

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) {

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;


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

step4:AndroidManifest.xml
复制代码 代码如下:

package="cn.roco.sensor"
android:versionCode="1"
android:versionName="1.0">


android:label="@string/app_name">







转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/165190.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号