Android implements the compass Function
(1) The layout file is as follows:
Required image:
(2) MainActivity. java
Import android. app. activity; import android. content. context; 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 {private ImageView imageView; private SensorManager manager; private SensorListener listener = new SensorListener (); @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); imageView = (ImageView) this. findViewById (R. id. imageView); imageView. setKeepScreenOn (true); manager = (SensorManager) getSystemService (Context. SENSOR_SERVICE) ;}@ Override protected void onResume () {Sensor sensor = manager. getdefasensensor (Sensor. TYPE_ORIENTATION); manager. registerListener (listener, sensor, SensorManager. SENSOR_DELAY_GAME); super. onResume () ;}@ Override protected void onPause () {manager. unregisterListener (listener); super. onPause ();} private final class SensorListener implements SensorEventListener {private float predegree = 0; public void onSensorChanged (SensorEvent event) {float degree = event. values [0]; // stores the direction value 90 RotateAnimation animation = new RotateAnimation (predegree,-degree, Animation. RELATIVE_TO_SELF, 0.5f, Animation. RELATIVE_TO_SELF, 0.5f); animation. setDuration (200); imageView. startAnimation (animation); predegree =-degree;} public void onAccuracyChanged (Sensor sensor, int accuracy ){}}}
The effect is as follows: