概要
現状のコードは JDK8 対応が中途半端なので、今回はきちんと JDK8 に対応してみようと思います。
やること
JDK8 対応する。
現行コード
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
defaultConfig {
applicationId "com.objectfanatics.chrono0015"
minSdkVersion 23
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
// TODO: jdk8 は要検討。
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
}
JDK8対応方針
◆ kotlin
kotlin については、JDK8 を一部サポートするコードの入っているバージョンを利用しようと思います。
具体的には、org.jetbrains.kotlin:kotlin-stdlib
を org.jetbrains.kotlin:kotlin-stdlib-jdk8
に変更するだけです。
詳細は Configuring Dependencies 参照のこと。
◆ desugaring
ソースコード上で java や kotlin を JDK8 に対応しても、アプリがサポート対象とする一部の実行環境に JDK8 の API が含まれていなという状況では Build.VERSION.SDK_INT
のチェック等による条件分岐が必要となり、保守が難しくなります。
そのため、この問題を Java 8+ API desugaring により対応します。
※詳細は Java 8+ API desugaring メモ 参照のこと。
変更後のコード
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
defaultConfig {
applicationId "com.objectfanatics.chrono0015"
minSdkVersion 23
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.10'
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
}
まとめ
今回は JDK8 への対応を行いました。
build.gradle はある程度整理できた気がするので、次回は build.gradle の kts 化をしてみようと思います。