Android 指南针
生活随笔
收集整理的這篇文章主要介紹了
Android 指南针
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
開發(fā)指南針?biāo)悸泛芎?jiǎn)單:準(zhǔn)備一張指南針圖片,該圖片上方向指針指向北方。接下來開發(fā)一個(gè)檢測(cè)方向的傳感器,程序檢測(cè)到手機(jī)頂部繞Z軸轉(zhuǎn)過多少度,讓指南針圖片反向轉(zhuǎn)過多少度即可。
程序代碼:
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;// 記錄指南針圖片轉(zhuǎn)過的角度float currentDegree = 0f;// 定義Sensor管理器SensorManager mSensorManager;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);// 獲取界面中顯示指南針的圖片znzImage = (ImageView) findViewById(R.id.znzImage);// 獲取傳感器管理服務(wù)mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);}@Overrideprotected void onResume() {super.onResume();// 為系統(tǒng)的方向傳感器注冊(cè)監(jiān)聽器mSensorManager.registerListener(this,mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),SensorManager.SENSOR_DELAY_GAME);}@Overrideprotected void onPause() {// 取消注冊(cè)mSensorManager.unregisterListener(this);super.onPause();}@Overrideprotected void onStop() {// 取消注冊(cè)mSensorManager.unregisterListener(this);super.onStop();}@Overridepublic void onSensorChanged(SensorEvent event) {// 獲取觸發(fā)event的傳感器類型int sensorType = event.sensor.getType();switch (sensorType) {case Sensor.TYPE_ORIENTATION:// 獲取繞Z軸轉(zhuǎn)過的角度。float degree = event.values[0];<strong>// 創(chuàng)建旋轉(zhuǎn)動(dòng)畫(反向轉(zhuǎn)過degree度)RotateAnimation ra = new RotateAnimation(currentDegree, -degree,Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f);</strong>// 設(shè)置動(dòng)畫的持續(xù)時(shí)間ra.setDuration(200);// 運(yùn)行動(dòng)畫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>
演示結(jié)果:
總結(jié)
以上是生活随笔為你收集整理的Android 指南针的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gps网络对时Linux,gps网络时间
- 下一篇: Android手势操作耍起来!