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

Android 取得螢幕解析度的方法與原始碼剖析

編輯:關於 Android 程式設計

在做界面適配的時候,常常需要螢幕的寬高。那麼該怎麼取得解析度?

實務上有兩種主流寫法。

方法一:透過 WindowManager 取得 Display

WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();

DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);

screenHeight = outMetrics.heightPixels;
screenWidth = outMetrics.widthPixels;

// screenHeight = display.getHeight(); 此種方法已廢棄
// screenWidth = display.getWidth();   此種方法已廢棄

從原始碼來看,以 height 為例:

private final Point mTmpPoint = new Point();

public int getHeight() {
    synchronized (mTmpPoint) {
        long now = SystemClock.uptimeMillis();
        if (now > (mLastGetTime + 20)) {
            getSizeInternal(mTmpPoint, true);
            mLastGetTime = now;
        }
        return mTmpPoint.y;
    }
}

核心是 mTmpPoint 的 y 座標,而它是在 getSizeInternal 中填入的:

private void getSizeInternal(Point outSize, boolean doCompat) {
    try {
        IWindowManager wm = getWindowManager();
        if (wm != null) {
            wm.getDisplaySize(outSize);
            CompatibilityInfo ci;
            if (doCompat && (ci = mCompatibilityInfo.getIfNeeded()) != null) {
                synchronized (mTmpMetrics) {
                    mTmpMetrics.noncompatWidthPixels = outSize.x;
                    mTmpMetrics.noncompatHeightPixels = outSize.y;
                    mTmpMetrics.density = mDensity;
                    ci.applyToDisplayMetrics(mTmpMetrics);
                    outSize.x = mTmpMetrics.widthPixels;
                    outSize.y = mTmpMetrics.heightPixels;
                }
            }
        } else {
            // 系統啟動早期的保險做法
            outSize.x = getRawWidth();
            outSize.y = getRawHeight();
        }
    } catch (RemoteException e) {
        Slog.w("Display", "Unable to get display size", e);
    }
}

可以看到兩條路徑:一條是透過 CompatibilityInfo 換算 metrics,另一條是 getRawHeight(),而它最終是一個 native 方法:

public int getRawHeight() {
    int h = getRawHeightNative();
    return h;
}

private native int getRawHeightNative();

方法二:直接從 Resource 拿 DisplayMetrics

DisplayMetrics metrics = context.getResources().getDisplayMetrics();
screenHeight = metrics.heightPixels;
screenWidth = metrics.widthPixels;

DisplayMetrics 的構成

不論走哪一條路,最終都是為了取得 DisplayMetrics。它定義了幾組標準密度常量:

public static final int DENSITY_LOW    = 120;  // 低
public static final int DENSITY_MEDIUM = 160;  // 中
public static final int DENSITY_TV     = 213;  // 720p TV
public static final int DENSITY_HIGH   = 240;  // 高
public static final int DENSITY_XHIGH  = 320;  // 超高

預設值由 setToDefaults() 設定:

public void setToDefaults() {
    widthPixels = 0;
    heightPixels = 0;
    density = DENSITY_DEVICE / (float) DENSITY_DEFAULT;
    densityDpi = DENSITY_DEVICE;
    scaledDensity = density;
    xdpi = DENSITY_DEVICE;
    ydpi = DENSITY_DEVICE;
    noncompatWidthPixels = 0;
    noncompatHeightPixels = 0;
}

而真正讓 metrics 填入正確數值的是 setTo(DisplayMetrics o),它把 widthPixels、heightPixels、density、densityDpi、scaledDensity、xdpi、ydpi 以及 noncompat 系列欄位全數複製過來。

Resource 是怎麼把 metrics 寫進去的

Resource 的建構式中呼叫了 updateConfiguration:

public Resources(AssetManager assets, DisplayMetrics metrics,
        Configuration config, CompatibilityInfo compInfo) {
    mAssets = assets;
    mMetrics.setToDefaults();
    mCompatibilityInfo = compInfo;
    updateConfiguration(config, metrics);
    assets.ensureStringBlocks();
}

public void updateConfiguration(Configuration config, DisplayMetrics metrics) {
    updateConfiguration(config, metrics, null);
}

public void updateConfiguration(Configuration config, DisplayMetrics metrics,
        CompatibilityInfo compat) {
    synchronized (mTmpValue) {
        if (compat != null) {
            mCompatibilityInfo = compat;
        }
        if (metrics != null) {
            mMetrics.setTo(metrics);
        }
        ...
    }
}

所以 Resources 產生的時候,metrics 就已經寫入完成。至於我們平常用的 getResources(),主要在 ContextThemeWrapper 中實作:

@Override
public Resources getResources() {
    if (mResources != null) {
        return mResources;
    }
    if (mOverrideConfiguration == null) {
        mResources = super.getResources();
        return mResources;
    } else {
        Context resc = createConfigurationContext(mOverrideConfiguration);
        mResources = resc.getResources();
        return mResources;
    }
}

可以看到它優先回傳快取,若設定了覆寫的 Configuration 則另建 Context 取得。更底層的實作仍要往下追到 native 層才能看全貌。

實務建議:優先使用方法二的 getResources().getDisplayMetrics(),程式碼最簡潔;若要計算實際可用區域,別忘了再扣掉狀態列與導覽列高度。

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