Java Android中的向后兼容性及其实现方法

Java Android中的向后兼容性及其实现方法,java,android,backwards-compatibility,Java,Android,Backwards Compatibility,我目前正在更新我维护的一个库,我想提供一个在方法签名中使用的方法,但是这仅在API 23+中可用。我知道Android文档指出,您应该通过以下检查确保向后兼容性: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // some API specific code 我还知道可以在文件夹命名的基础上定制资源,例如layout-v13。我的问题是,是否可以添加这种检查或类似的检查,以便我的代码仍能在

我目前正在更新我维护的一个库,我想提供一个在方法签名中使用的方法,但是这仅在API 23+中可用。我知道Android文档指出,您应该通过以下检查确保向后兼容性:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    // some API specific code
我还知道可以在文件夹命名的基础上定制资源,例如
layout-v13
。我的问题是,是否可以添加这种检查或类似的检查,以便我的代码仍能在
@Version Build.VERSION_CODES.HONEYCOMB // not real code, just what I'm thinking
public void setData(MediaDataSource mediaDataSource) {
    // some code
}

是的,通常当您遇到API compat问题时,当您按下警告上的
alt+enter
时,Android Studio会为您提供多种解决方案

以Android中仅对Oreo用户可用的
NotificationChannel
为例(API 26)。你有以下目标

选项1:If-else语句 你在问题中已经提到了这一点

选项2:@TargetAPI注释

@TargetApi(Build.VERSION_CODES.O)
private void createNotification() {
NotificationChannel notificationChannel = new NotificationChannel("123", "newNotification", NotificationManager.IMPORTANCE_DEFAULT);}
@RequiresApi(api = Build.VERSION_CODES.O)
private void createNotification() {
NotificationChannel notificationChannel = new NotificationChannel("123", "newNotification", NotificationManager.IMPORTANCE_DEFAULT);
}
选项3:@RequiresAPI注释

@TargetApi(Build.VERSION_CODES.O)
private void createNotification() {
NotificationChannel notificationChannel = new NotificationChannel("123", "newNotification", NotificationManager.IMPORTANCE_DEFAULT);}
@RequiresApi(api = Build.VERSION_CODES.O)
private void createNotification() {
NotificationChannel notificationChannel = new NotificationChannel("123", "newNotification", NotificationManager.IMPORTANCE_DEFAULT);
}