0
0

More than 3 years have passed since last update.

Context#getDisplayでクラッシュ

Posted at

画面のサイズを取得するために以下の実装をしていたのですが、Android 6.0(Marshmallow)でクラッシュしていました。(Android 7.0ではクラッシュしなかった)

val displayMetrics = DisplayMetrics().apply {
    // ここでクラッシュ
    context.display?.getRealMetrics(this)
}

developers によると、API Level 30(Android10)からContext#getDisplayを使って下さいとのことだったので、API Level 30未満の処理を追加しました。

// API Level 30未満の処理
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
windowManager.defaultDisplay.getRealMetrics(this)

WindowManager#getDefaultDisplayはAPI Level 30から非推奨になります。

以下、全体の実装です。

val displayMetrics = DisplayMetrics().apply {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        context.display?.getRealMetrics(this)
    } else {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        windowManager.defaultDisplay.getRealMetrics(this)
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0