我正在尝试实现一些在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有条件编译吗?
任何帮助都将不胜感激!
发布于 2018-05-15 16:30:41
这个问题已经用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);
}
}现在,它的工作没有任何错误。我希望它能帮到别人。
https://stackoverflow.com/questions/50351431
复制相似问题