Android 指南针
生活随笔
收集整理的這篇文章主要介紹了
Android 指南针
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
開發指南針思路很簡單:準備一張指南針圖片,該圖片上方向指針指向北方。接下來開發一個檢測方向的傳感器,程序檢測到手機頂部繞Z軸轉過多少度,讓指南針圖片反向轉過多少度即可。
程序代碼:
package org.crazyit.sensor;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 Compass extends Activity implements SensorEventListener {// 定義顯示指南針的圖片ImageView znzImage;// 記錄指南針圖片轉過的角度float currentDegree = 0f;// 定義Sensor管理器SensorManager mSensorManager;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);// 獲取界面中顯示指南針的圖片znzImage = (ImageView) findViewById(R.id.znzImage);// 獲取傳感器管理服務mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);}@Overrideprotected void onResume() {super.onResume();// 為系統的方向傳感器注冊監聽器mSensorManager.registerListener(this,mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),SensorManager.SENSOR_DELAY_GAME);}@Overrideprotected void onPause() {// 取消注冊mSensorManager.unregisterListener(this);super.onPause();}@Overrideprotected void onStop() {// 取消注冊mSensorManager.unregisterListener(this);super.onStop();}@Overridepublic void onSensorChanged(SensorEvent event) {// 獲取觸發event的傳感器類型int sensorType = event.sensor.getType();switch (sensorType) {case Sensor.TYPE_ORIENTATION:// 獲取繞Z軸轉過的角度。float degree = event.values[0];<strong>// 創建旋轉動畫(反向轉過degree度)RotateAnimation ra = new RotateAnimation(currentDegree, -degree,Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f);</strong>// 設置動畫的持續時間ra.setDuration(200);// 運行動畫znzImage.startAnimation(ra);currentDegree = -degree;break;}}@Overridepublic void onAccuracyChanged(Sensor sensor, int accuracy) {} } 布局文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:background="#fff"android:orientation="vertical" ><ImageViewandroid:id="@+id/znzImage"android:layout_width="fill_parent"android:layout_height="fill_parent"android:scaleType="fitCenter"android:src="@drawable/znz" /></LinearLayout>
演示結果:
總結
以上是生活随笔為你收集整理的Android 指南针的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gps网络对时Linux,gps网络时间
- 下一篇: 《消费者行为学》读后感_20171129