android指南針—核心代碼

來源:互聯網
上載者:User

指南針一直是一個不可或缺的重要的角色

開發指南針的思路很簡單,程式先準備一張指南針圖片,讓圖片上方向的指標,指向正北方,接下來開發檢測方向的感應器,程式檢測到手機頂部繞過Zf軸多少度,讓指南針的圖片,反向轉過多少度即可。

主要代碼如下

package com.example.compass;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 MainActivity extends Activity implements SensorEventListener {// 定義顯示指南針的圖片ImageView znzImage;// 記錄指南針圖片轉過的角度float currentDegree = 0f;// 定義真機的Sensor管理器SensorManager mSensorManager;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);System.out.println("MainActivity.onCreate()");setContentView(R.layout.activity_main);// 擷取介面中顯示指南針的圖片znzImage = (ImageView) findViewById(R.id.znzImage);// 擷取真機的感應器管理服務mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);}@Overrideprotected void onResume() {super.onResume();System.out.println("MainActivity.onResume()");// 為系統的方向感應器註冊監聽器mSensorManager.registerListener(this,mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),SensorManager.SENSOR_DELAY_GAME);}@Overrideprotected void onPause() {System.out.println("MainActivity.onPause()");// 取消註冊mSensorManager.unregisterListener(this);super.onPause();}@Overrideprotected void onStop() {System.out.println("MainActivity.onStop()");// 取消註冊mSensorManager.unregisterListener(this);super.onStop();}public void onSensorChanged(SensorEvent event) {System.out.println("MainActivity.onSensorChanged()");// 真機上擷取觸發event的感應器類型int sensorType = event.sensor.getType();// 模擬器上擷取觸發event的感應器類型switch (sensorType) {case Sensor.TYPE_ORIENTATION:// 擷取繞Z軸轉過的角度。float degree = event.values[0];// 建立旋轉動畫(反向轉過degree度)RotateAnimation ra = new RotateAnimation(currentDegree, -degree,Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f);// 設定動畫的期間ra.setDuration(200);// 運行動畫znzImage.startAnimation(ra);currentDegree = -degree;break;}}public void onAccuracyChanged(Sensor sensor, int accuracy) {System.out.println("MainActivity.onAccuracyChanged()");}}

是吧,很簡單吧,沒有想象的那麼難。實際上就是根據感應器傳回來的資料處理動畫,傳回來的第一個資料,就是繞Z軸旋轉的角度。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.