【问题标题】:Android - conditional compilingAndroid - 条件编译
【发布时间】:2023-03-05 12:23:01
【问题描述】:

我正在尝试实现一些应该在 Android 4.0 到 8.0 版本上运行的代码。问题是库 (jar) 中的代码和最终用户可能希望使用较旧的 Android 版本而不是 8.0 (Oreo) 编译他的应用程序(使用我的库)。结果,他会得到一个错误java.lang.Error: Unresolved compilation problems

看看下面的代码:

NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    //Build.VERSION_CODES.O is not defined in older versionof Android
    //So, I have to use a numeric value (26)
    //My Build.VERSION.SDK_INT = 21 (Lollipop)
    if (Build.VERSION.SDK_INT >= 26) {   
    //The next code is executed even if Build.VERSION.SDK_INT < 26 !!!          
        android.app.NotificationChannel channel = new android.app.NotificationChannel(
                NOTIFICATION_CHANNEL_ID,"ID_CHANNEL", NotificationManager.IMPORTANCE_LOW);

        channel.setShowBadge(false);
        channel.enableLights(true);
        channel.setLockscreenVisibility(android.app.Notification.VISIBILITY_PUBLIC);

        notificationManager.createNotificationChannel(channel);
    } 

所以,即使Build.VERSION.SDK_INT &lt; 26 条件中的代码被执行并给出错误!如果用户使用旧版本的 Android(如 KITKATLOLLIPOP)编译他的项目,我该如何省略此代码? Android有条件编译吗?

任何帮助将不胜感激!

【问题讨论】:

标签: java android compilation


【解决方案1】:

问题已通过使用android.annotation.TargetApi 解决。 所以,我重写了我的代码,如下所示:

@TargetApi(26)
private void createNotificationChannel(NotificationManager notificationManager){
    android.app.NotificationChannel channel = new android.app.NotificationChannel(
            NOTIFICATION_CHANNEL_ID, "ID_CHANNEL", NotificationManager.IMPORTANCE_LOW);

    channel.setShowBadge(false);
    channel.enableLights(true);
    channel.setLockscreenVisibility(android.app.Notification.VISIBILITY_PUBLIC);

    notificationManager.createNotificationChannel(channel);
}

public void init(Context context){
   NotificationManager notificationManager = (NotificationManager) context
        .getSystemService(Context.NOTIFICATION_SERVICE);

   //Build.VERSION_CODES.O is not defined in older version of Android
   //So, I have to use a numeric value (26)
   //My Build.VERSION.SDK_INT = 21 (Lollipop)
   if (Build.VERSION.SDK_INT >= 26) {   
      createNotificationChannel(notificationManager); 
   }
}

现在它可以正常工作了。我希望它可以帮助别人。

【讨论】:

    猜你喜欢
    • 2019-12-26
    • 2010-11-15
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多