Android中的向后兼容性和方法

时间:2017-12-26 04:37:01

标签: java android backwards-compatibility

我正在更新我维护的库,我想提供一种在方法签名中使用MediaDataSource的方法,但这只适用于API 23+。我知道Android文档声明您应该通过以下检查确保向后兼容性:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    // some API specific code

我也知道可以在文件夹命名上自定义资源,例如layout-v13。我的问题是,是否可以添加此类检查或类似的检查,以便我的代码仍可用于< API 23. Android是否提供如下构造:

@Version Build.VERSION_CODES.HONEYCOMB // not real code, just what I'm thinking
public void setData(MediaDataSource mediaDataSource) {
    // some code
}

1 个答案:

答案 0 :(得分:2)

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

以Android中NotificationChannel为例,仅供奥利奥用户使用(API 26)。您有以下内容来定位它们。

选项1:如果是其他声明 您已经在问题中提到了这一点

选项2: @TargetAPI注释

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

选项3: @RequiresAPI Annotation

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