安卓感應器開發之指南針,安卓感應器指南針
代碼很簡單,主要是一些常用感應器的監聽,指南針還是挺好用的。
布局代碼
<?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:background="#fff"><ImageViewandroid:id="@+id/znzImage"android:layout_width="fill_parent"android:layout_height="fill_parent"android:scaleType="fitCenter"android:src="@drawable/compass" /></LinearLayout>
程式碼:
package zhinanzheng.com;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;/** * @author coderwry 653866417@qq.com * @version 1.0 */public class Zhinanzheng extends Activity implements SensorEventListener{ImageView image; //指南針圖片float currentDegree = 0f; //指南針圖片轉過的角度SensorManager mSensorManager; //管理器 /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); image = (ImageView)findViewById(R.id.znzImage); mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); //擷取管理服務 } @Override protected void onResume(){ super.onResume(); //註冊監聽器 mSensorManager.registerListener(this , mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME); } //取消註冊 @Override protected void onPause(){ mSensorManager.unregisterListener(this); super.onPause(); } @Override protected void onStop(){ mSensorManager.unregisterListener(this); super.onStop(); } //感應器值改變@Overridepublic void onAccuracyChanged(Sensor sensor, int accuracy) {// TODO Auto-generated method stub} //精度改變@Overridepublic void onSensorChanged(SensorEvent event) {// TODO Auto-generated method stub//擷取觸發event的感應器類型int sensorType = event.sensor.getType();switch(sensorType){case Sensor.TYPE_ORIENTATION:float degree = event.values[0]; //擷取z轉過的角度//穿件旋轉動畫RotateAnimation ra = new RotateAnimation(currentDegree,-degree,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f); ra.setDuration(100);//動畫期間 image.startAnimation(ra); currentDegree = -degree; break;}}}