有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Android中的java向后兼容性和方法

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

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

我还知道,可以根据文件夹命名对资源进行定制,例如layout-v13。我的问题是,是否可以添加此类检查或类似的检查,以便我的代码仍能工作<;API 23。安卓系统是否提供了如下构造:

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

共 (1) 个答案

  1. # 1 楼答案

    是的,通常当你遇到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);}
    

    选项3:@RequiresAPI注释

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