Java Android-条件编译
我正在尝试实现一些可以在Android上运行的代码,从4.0版到8.0版。问题是库(jar)中的代码和最终用户可能希望使用较旧的Android版本而不是8.0(Oreo)编译他的应用程序(使用我的库)。结果,他将得到一个错误Java Android-条件编译,java,android,compilation,Java,Android,Compilation,我正在尝试实现一些可以在Android上运行的代码,从4.0版到8.0版。问题是库(jar)中的代码和最终用户可能希望使用较旧的Android版本而不是8.0(Oreo)编译他的应用程序(使用我的库)。结果,他将得到一个错误java.lang.error:未解决的编译问题 请看下面的代码: NotificationManager notificationManager = (NotificationManager) context .getSystemService(Co
java.lang.error:未解决的编译问题
请看下面的代码:
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);
}
NotificationManager NotificationManager=(NotificationManager)上下文
.getSystemService(上下文通知服务);
//旧版本的Android中未定义Build.VERSION_CODES.O
//因此,我必须使用一个数值(26)
//My Build.VERSION.SDK_INT=21(棒棒糖)
如果(Build.VERSION.SDK_INT>=26){
//即使Build.VERSION.SDK_INT<26,也会执行下一个代码!!!
android.app.NotificationChannel=新的android.app.NotificationChannel(
通知渠道ID,“ID渠道”,通知经理。重要性低);
频道设置显示卡(假);
通道启用灯(真);
channel.setLockscreenVisibility(android.app.Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(频道);
}
因此,即使Build.VERSION.SDK_INT<26
执行条件中的代码并给出错误!如果用户使用较旧版本的Android(如KITKAT
或LOLLIPOP
)编译项目,我怎么能省略此代码?
Android有条件编译吗
任何帮助都将不胜感激 这个问题已经通过使用
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);
}
}
现在它工作正常,没有任何错误。我希望它能帮助别人 可能重复的