package com.pas.classic.compass; import com.pas.compass.R; import cn.waps.AdInfo; import cn.waps.AppConnect; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.provider.ContactsContract.AggregationExceptions; import android.app.Activity; import android.view.Menu; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.AdapterViewFlipper; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private SensorManager sm; private ImageView iv_compass; MyListener listener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sm = (SensorManager) getSystemService(SENSOR_SERVICE); iv_compass = (ImageView) findViewById(R.id.iv_compass); // 獲得方向傳感器 Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION); if (sensor == null) { Toast.makeText(this, "您的手機沒有方向感應器,即將退出", Toast.LENGTH_LONG).show(); finish(); return; } listener = new MyListener(); sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_FASTEST); } private class MyListener implements SensorEventListener { float startangle = 0f; /** * 傳感器數據變化執行 */ @Override public void onSensorChanged(SensorEvent event) { /** * 方向傳感器時 此值表明與正北的角度 */ float angle = Math.round(event.values[0]); rotate(angle); startangle = -angle; } private void rotate(float angle) { RotateAnimation animation = new RotateAnimation(startangle, angle, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animation.setDuration(3000); animation.setFillAfter(true); iv_compass.startAnimation(animation); } /** * 精確度發生變化 好比進入強磁場區收到干擾 */ @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } } @Override protected void onDestroy() { sm.unregisterListener(listener); super.onDestroy(); } }