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!

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.