首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android -条件编译

Android -条件编译
EN

Stack Overflow用户
提问于 2018-05-15 13:25:28
回答 1查看 1K关注 0票数 0

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

看看下面的代码:

代码语言:javascript
复制
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 < 26在一个条件内的代码被执行并给出一个错误!如果用户使用较早版本的Android (如KITKATLOLLIPOP )编译他的项目,我如何省略这段代码?Android有条件编译吗?

任何帮助都将不胜感激!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-15 16:30:41

这个问题已经用android.annotation.TargetApi解决了。因此,我重写了代码,如下所示:

代码语言:javascript
复制
@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); 
   }
}

现在,它的工作没有任何错误。我希望它能帮到别人。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50351431

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档