編輯:關於 Android 程式設計
先前有网友私信問:做過磁場感測器,能做出指南針嗎?其實在第一篇就提過,磁場感測器做得到,只是演算法麻煩得多。最簡便的指南針可以用方向感測器實作。一直忙到現在才有空寫這篇,先上圖:

版面配置很簡單,就一張指南針的平面圖:
<ImageView
android:id="@+id/main_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/bg" />
演算法在上一篇也提過:values[0] 代表方位角,也就是手機繞 Z 軸旋轉的角度。0 表示北(North),90 表示東(East),180 表示南(South),270 表示西(West)。當手機水平放置且 values[0] 剛好落在這四個值上,代表手機正前方就對應 those 方向——這正是電子羅盤的基礎。
因此思路很直白:拿到 values[0],再把指針圖片反向旋轉同樣的角度,指針就會永遠指向真北。
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == 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);
ra.setFillAfter(true); // 動畫結束後保留狀態
image.startAnimation(ra);
currentDegree = -degree;
}
}
用 currentDegree 記錄目前角度、動畫只做差值旋轉,可以避免指針每帧都從 0 開始轉而產生的跳動。
public class OrientationActivity extends Activity implements SensorEventListener {
private TextView tv_context;
private Sensor mAccelerometer;
private SensorManager mSensorManager;
private float currentDegree = 0f; // 記錄指南針圖片轉過的角度
private ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_orien);
infoViews();
}
private void infoViews() {
tv_context = (TextView) findViewById(R.id.tv_context);
tv_context.setText("指南針");
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
image = (ImageView) findViewById(R.id.main_iv);
}
@Override
protected void onResume() {
if (mAccelerometer != null) {
mSensorManager.registerListener(this, mAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
Toast.makeText(getApplicationContext(), "此裝置有方向感測器", 0).show();
} else {
Toast.makeText(getApplicationContext(), "此裝置沒有方向感測器", 0).show();
}
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this); // 記得反註冊,否則耗電
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) { }
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
float degree = event.values[0];
RotateAnimation ra = new RotateAnimation(currentDegree, -degree,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
ra.setDuration(200);
ra.setFillAfter(true);
image.startAnimation(ra);
currentDegree = -degree;
}
}
}
需要更精細的定位資訊時,可以改用 Criteria 挑選合適的 location provider:
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); // 最高精度
criteria.setAltitudeRequired(false); // 不需要海拔
criteria.setBearingRequired(false); // 不需要方位
criteria.setCostAllowed(true); // 允許付費來源
criteria.setPowerRequirement(Criteria.POWER_LOW); // 低耗電
Location location = locationManager.getLastKnownLocation(
locationManager.getBestProvider(criteria, true));
再以 LocationListener 接收更新:
LocationListener listener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
if (status != LocationProvider.OUT_OF_SERVICE) {
updateLocation(mLocationManager.getLastKnownLocation(mLocationProvider));
} else {
mLocationTextView.setText(R.string.cannot_get_location);
}
}
@Override public void onProviderEnabled(String provider) { }
@Override public void onProviderDisabled(String provider) { }
@Override
public void onLocationChanged(Location location) {
updateLocation(location);
}
};
第一,TYPE_ORIENTATION 在 API 8 之後已被標示為 deprecated。新專案建議改用 TYPE_ACCELEROMETER 搭配 TYPE_MAGNETIC_FIELD,透過 SensorManager.getRotationMatrix() 與 getOrientation() 自行計算方位角,這樣在愈來愈多新機上都能穩定運作。
第二,寫的過程中我一直有個疑問:values[0] 是從一開始就綁好東南西北的嗎?否則怎麼可能一啟動就指向北?這部分牽涉到感測器座標系與裝置出廠校準的關係,若有清楚答案歡迎指教。
DialogFragment 完整指南:Android 官方推薦的對話框實現方式
一、概述 DialogFragment 從 Android 3.0 開始引入,它是一種特殊的 Fragment,用於在 Activity 內容之上顯示一個模態對話框,典型
[Android 開發系列] 動手做一個 IT 博客聚合瀏覽器
1. 先談談那個「坑」 坦白說,這篇之前欠下的帳有點多。先前開頭的兩個 Android 開發教學系列,寫到後面實在提不起勁,就先擱著了,這裡說聲抱歉。不過原始碼都有放在
Android AsyncTask 原理剖析與 Java 多線程探索
一、Java 線程 Thread 在 Java 中最常見的起線程方式,就是 new Thread 然後覆寫 run 方法。新線程執行的程式碼就是 run 函式。 new
Android 中切換主題或皮膚的實現方式
1. 簡介 在 Android 中切換主題或皮膚,常見做法是將顏色、大小等資源配置放入額外的 APK 或資源包,並在執行時動態載入。這種方式可讓主題資源與主程式分離,方便