生活随笔
收集整理的這篇文章主要介紹了
25-方向传感器实现指南针
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
傳感器:手機常用傳感器有方向傳感器、重力傳感器、光線傳感器等。
上北0度 右東90度 下南180度 左西 270度
MainActivity
Sensor.TYPE_ORIENTATION? 方向傳感器
Sensor.TYPE_ACCELEROMETER? 重力
Sensor.TYPE_LIGHT? 光線
Sensor.TYPE_MAGNETIC_FIELD? 磁場
Sensor.TYPE_PROXIMITY 距離
Sensor.TYPE_TEMPERATURE 溫度
采樣率
SensorManager.SENSOR_DELAY_FASTEST 最快 不推薦,耗電最大,算法不好會影響ui性能
SensorManager.SENSOR_DELAY_GAME? 實時性較高的游戲使用該級別
SensorManager.SENSOR_DELAY_NORMAL 標準延遲,過低對賽車有跳幀現象
SensorManager.SENSOR_DELAY_UI? 用戶界面,游戲不推薦,相對省電
注冊監聽
package cn.itcast.sensor;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();@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);imageView = (ImageView) this.findViewById(R.id.imageView);imageView.setKeepScreenOn(true);manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);}@Overrideprotected void onResume() {Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION);//方向傳感器 其他一樣manager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME);//第3個參數為采樣率super.onResume();}@Overrideprotected void onPause() { //一旦離開前臺則取消 因為傳感器很耗電manager.unregisterListener(listener);super.onPause();}private final class SensorListener implements SensorEventListener{private float predegree = 0;
//測量到數據后調用此方法public void onSensorChanged(SensorEvent event) {float degree = event.values[0];//存放了方向值 90RotateAnimation 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;}public void onAccuracyChanged(Sensor sensor, int accuracy) {}}}main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"android:gravity="center">
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/zn"android:id="@+id/imageView"/>
</LinearLayout>
總結
以上是生活随笔為你收集整理的25-方向传感器实现指南针的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。