我正在尝试实现一些适用于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 < 26
条件中的代码被执行并出错!如果用户使用旧版Android(例如KITKAT
或LOLLIPOP
)编译项目,我该如何省略此代码?
是否有针对Android的条件编译?
任何帮助将不胜感激!
答案 0 :(得分: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);
}
}
现在它没有任何错误。我希望它可以帮助别人。