Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

코틀린(Kotlin)으로 안드로이드 API 버전을 프로그래밍 방식으로 확인하는 방법


이 글에서는 Kotlin(코틀린)을 사용해 안드로이드 기기의 API 버전(API 레벨)을 프로그래밍 방식으로 조회하는 방법을 단계별로 알아봅니다.

핵심 원리: Build.VERSION.SDK_INT

안드로이드는 현재 기기에서 실행 중인 OS의 API 레벨을 정수 값으로 제공합니다. 이 값은 android.os.Build.VERSION.SDK_INT 필드 하나만으로 손쉽게 얻을 수 있으며, 특정 기능을 특정 안드로이드 버전 이상에서만 동작하도록 분기 처리할 때 가장 널리 쓰이는 방식입니다.

1단계 — 새 프로젝트 만들기

Android Studio에서 File → New Project 메뉴로 이동한 뒤, 필요한 항목을 모두 입력하여 새 프로젝트를 생성합니다. 이때 언어는 반드시 Kotlin으로 선택하세요.

2단계 — 레이아웃 작성 (activity_main.xml)

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면에는 타이틀 텍스트, API 버전을 표시할 TextView, 그리고 클릭 시 버전 정보를 가져오는 Button이 배치됩니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="50dp"
      android:text="Tutorials Point"
      android:textAlignment="center"
      android:textColor="@android:color/holo_green_dark"
      android:textSize="32sp"
      android:textStyle="bold" />
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_above="@id/button"
      android:layout_centerInParent="true"
      android:layout_marginBottom="12sp"
      android:text=""
      android:textSize="24sp"
      android:textStyle="bold|italic" />
   <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="Get Android API Version"
      android:textSize="16sp"
      android:textStyle="bold" />
</RelativeLayout>

3단계 — MainActivity.kt 구현

src/MainActivity.kt에 다음 코드를 작성합니다. 버튼을 클릭하면 Build.VERSION.SDK_INT 값을 읽어와 when 문으로 각 API 레벨에 해당하는 버전 이름을 화면에 출력합니다.

import android.os.Build
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   lateinit var button: Button
   lateinit var textView: TextView
   var androidVersion = 0
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      textView = findViewById(R.id.textView)
      button = findViewById(R.id.button)
      button.setOnClickListener {
         androidVersion = Build.VERSION.SDK_INT
         when (androidVersion) {
            14 −> textView.text = "15, Ice Cream Sandwich"
            15 −> textView.text = "15, Ice Cream Sandwich"
            16 −> textView.text = "16, Jelly Bean"
            17 −> textView.text = "17, Jelly Bean"
            18 −> textView.text = "18, Jelly Bean"
            19 −> textView.text = "19, KitKat"
            21 −> textView.text = "21, Lollipop"
            22 −> textView.text = "22, Lollipop"
            23 −> textView.text = "23, Marshmallow"
            24 −> textView.text = "24, Nougat"
            25 −> textView.text = "25, Nougat"
            26 −> textView.text = "26, Oreo"
            27 −> textView.text = "27, Oreo"
            28 −> textView.text = "28, Pie"
            29 −> textView.text = "29, Android Q"
            else −> Toast.makeText(this@MainActivity, "Not Found", Toast.LENGTH_LONG).show()
         }
      }
   }
}

참고: 주요 API 레벨과 버전명 매핑

SDK_INT 값과 안드로이드 버전명의 대표적인 매핑은 다음과 같습니다.

  • 19 → KitKat(킷캣)
  • 21~22 → Lollipop(롤리팝)
  • 23 → Marshmallow(마시멜로)
  • 24~25 → Nougat(누가)
  • 26~27 → Oreo(오레오)
  • 28 → Pie(파이)
  • 29 → Android 10(Q)
  • 30 → Android 11(R)
  • 31~32 → Android 12(S)
  • 33 → Android 13(Tiramisu)
  • 34 → Android 14(Upside Down Cake)

예제 코드에 없는 최신 버전도 같은 방식으로 when 분기를 추가하면 됩니다. 또한 사용자에게 보여줄 버전 문자열이 필요하다면 Build.VERSION.RELEASE(예: "13")를 함께 활용하는 것이 좋습니다.

4단계 — AndroidManifest.xml 설정

androidManifest.xml에 아래 코드를 추가합니다. 일반적인 빈 프로젝트라면 대부분 자동 생성되어 있는 내용이므로, 패키지 이름(package)만 실제 프로젝트에 맞게 수정하면 됩니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

앱 실행 및 결과 확인

실제 안드로이드 스마트폰을 컴퓨터에 연결한 상태라고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후, 툴바의 Run(실행) 아이콘코틀린(Kotlin)으로 안드로이드 API 버전을 프로그래밍 방식으로 확인하는 방법을 클릭하세요. 기기 선택 창에서 본인의 모바일 기기를 고르면, 잠시 후 기기에 앱이 실행되어 기본 화면이 표시됩니다.

코틀린(Kotlin)으로 안드로이드 API 버전을 프로그래밍 방식으로 확인하는 방법