</pre><pre code_snippet_id="1840629" snippet_file_name="blog_20160819_2_6137175" name="code" class="java">方便好用,界面簡潔。
先上圖
</pre><pre code_snippet_id="1840629" snippet_file_name="blog_20160819_4_2691612" name="code" class="java"></pre><pre code_snippet_id="1840629" snippet_file_name="blog_20160819_4_2691612" name="code" class="java">
<pre name="code" class="java">package co.cn.com.conpass;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
public class MainActivity extends Activity implements SensorEventListener {
ImageView image,imageView1; //指南針圖片
float currentDegree = 0f; //指南針圖片轉過的角度
SensorManager mSensorManager; //管理器
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
image = (ImageView)findViewById(R.id.image);
imageView1 = (ImageView) findViewById(R.id.short_ima);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); //獲取管理服務
}
@Override
protected void onResume(){
super.onResume();
//註冊監聽器
mSensorManager.registerListener((SensorEventListener) 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();
}
//傳感器值改變
@Override
public void onSensorChanged(SensorEvent event) {
// 獲取觸發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);
imageView1.setAnimation(ra);
currentDegree = -degree;
break;
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
//精度改變
// public 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;
//
// }
// }
}