在 Android 的 coreLibraryDesugaring 中,提供了一些在 API 等级 26 上尚未可用的 Java 功能。下面是一个包含代码示例的解决方法:
首先,确保你的项目使用了 Android Gradle 插件 4.0.0 或更高版本。
在你的项目的 build.gradle 文件中,启用 coreLibraryDesugaring:
android {
compileOptions {
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}
java.time.LocalDateTime
类:import java.time.LocalDateTime;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocalDateTime now = LocalDateTime.now();
Log.d("MainActivity", "Current time: " + now);
}
}
这样,你的应用就可以在 API 等级 26 上使用 java.time.LocalDateTime
类了。当你运行应用时,coreLibraryDesugaring 会自动转换这些代码,以便在 API 等级 26 上正常运行。
需要注意的是,coreLibraryDesugaring 并不是对所有的 Java 功能都提供支持,它只支持一些常用的功能。如果你需要使用其他的 Java 功能,可能需要考虑使用其他的兼容库或者自行处理。