0

I am trying to implement some code that should work on Android beginning from version 4.0 to 8.0. The problem is that the code within a library (jar) and the end user may want to compile his app (with my library) using older Android version rather than 8.0 (Oreo). As a result, he will get an error java.lang.Error: Unresolved compilation problems.

Take a look at the code below:

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);
    } 

So, even if Build.VERSION.SDK_INT < 26 the code within a condition is executed and gives an error! How can I omit this code if the user compile his project using older version of Android like KITKAT or LOLLIPOP? Is there a conditional compilation for Android?

Any help will be appreciated!

Nolesh
  • 6,848
  • 12
  • 75
  • 112
  • Possible duplicate of [Java conditional compilation: how to prevent code chunks from being compiled?](https://stackoverflow.com/questions/4526113/java-conditional-compilation-how-to-prevent-code-chunks-from-being-compiled) –  May 15 '18 at 13:38

1 Answers1

2

The problem has been solved by using android.annotation.TargetApi. So, I rewrote my code as shown below:

@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); 
   }
}

Now it works without any errors. I hope it helps someone else.

Nolesh
  • 6,848
  • 12
  • 75
  • 112