Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 技術總結(013)——設定相機預覽角度(相容 API 2.2 以下版本)

編輯:關於 Android 程式設計

在 Android 2.2 以上版本中,我們可以直接呼叫 setDisplayOrientation 來設定相機的預覽角度。但若是要相容 2.2 以下的舊版本,由於該方法尚未公開,就必須透過反射的方式來呼叫。以下是一個相容舊版本的實作:

[java]
/**
 * 設定相機的預覽角度,2.2 以上可直接使用 setDisplayOrientation
 *
 * @param orientation 相機的預覽角度
 */
private void setDisplayOrientation(int orientation) {
    Method setCameraDisplayOrientation;
    try {
        // 透過反射,取得對應的方法
        setCameraDisplayOrientation = mCamera.getClass().getMethod(
                "setDisplayOrientation", new Class[] { int.class });
        if (setCameraDisplayOrientation != null) {
            setCameraDisplayOrientation.invoke(mCamera,
                    new Object[] { orientation });
        }
    } catch (Exception e) {
        MobclickAgent.reportError(
                mContext,
                getResources().getString(
                          R.string.umeng_error_set_display_orientation));
        e.printStackTrace();
    }
}

這裡透過 getMethod 取得 setDisplayOrientation 方法,再用 invoke 動態呼叫。若執行過程中發生例外,則透過 MobclickAgent 回報錯誤,方便後續追蹤問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved