画面のサイズを取得するために以下の実装をしていたのですが、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)
}
}