You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android低版本使用LocalDate等java.time API兼容方案

Android低版本设备兼容Java 8时间API方案

问题背景

调用java.time包下时间相关方法时,抛出minSdkVersion不匹配报错:
The application's minSdkVersion is newer than the device API level(应用minSdkVersion高于设备API级别)
涉及调用的代码如下:

LocalDate.now();
YearMonth yearMonth = YearMonth.from(date);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy");
String recher_mois=date.format(formatter).toString();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy");
  • 上述API原生支持的最低Android API级别为26,测试所用平板API级别仅为22
  • 同安装包在高系统版本(满足API 26+要求)的手机上可正常运行

兼容方案

无需更换高系统版本测试设备,开启Android核心库脱糖(coreLibraryDesugaring)即可在API 22设备上正常使用上述Java 8时间API,对应Gradle配置如下:

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.example.calendriernew"
        minSdk 22
        targetSdk 32
        versionCode 2
        versionName "1.0"

        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    compileOptions {
        // 开启新版Java语言API脱糖支持
        coreLibraryDesugaringEnabled true
        // 设置Java兼容版本为1.8
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    // 引入脱糖核心库依赖
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9'
}

配置后安装异常处理

配置修改完成后,可能遇到如下安装失败报错:

Installation failed due to: 'Failed to commit install session 1719068954 with command pm install-commit 1719068954. Error: INSTALL_FAILED_VERIFICATION_FAILURE'

该问题不属于代码或配置错误,排查步骤:

  • 先尝试升级测试平板系统版本,若问题仍存在
  • 直接重启测试设备,重启后即可正常安装,时间API可在低版本系统上正常调用。

内容的提问来源于stack exchange,提问作者tidave971

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 10:24:18