在我的Android项目中,我在清单文件中将minSdkVersion
设置为19
和targetSdkVersion
26
。在其中一个Java文件中,我使用两个不同的API调度警报,使用if语句检查当前版本的Android:
private void scheduleAlarm(AlarmManager alarmManager, long targetTime, PendingIntent pendingIntent, Intent intent) {
if(VersionCheckUtils.isLollipopOrLater()) { // Lollipop is version 21
// Code for versions after Lollipop
logAlarm(targetTime, pendingIntent, intent, "Lollipop");
alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(targetTime, pendingIntent),
pendingIntent);
}
else {
// Code for older versions
logAlarm(targetTime, pendingIntent, intent, "Kitkat");
alarmManager.setExact(AlarmManager.RTC_WAKEUP, targetTime, pendingIntent);
}
}
现在Lint不分析if
语句并报告此错误:
NewApi: Calling new methods on older versions
../../src/main/java/org/bee/beezone/trafficcontrol/AlarmScheduler.java:61: Call requires API level 21 (current min is 19): android.app.AlarmManager#setAlarmClock
你怎么能处理这种情况?代码实际上应该是安全的,但Android lint似乎并不理解这一点。
最后,我通过将这些行添加到gradle构建文件中来停用“NewApi”检查:
android {
...
lintOptions {
disable 'NewApi'
}
}
有没有更好的方法来应对这种情况?
答案 0 :(得分:1)
我认为你得到错误是因为你在一个方法中混合了两种不同api版本的方法。
你可以:
或
移出if条件中的代码并使用@TargetApi(n)注释
private void scheduleAlarm(AlarmManager alarmManager, long targetTime, PendingIntent pendingIntent, Intent intent) {
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Lollipop is version 21
// Code for versions after Lollipop
alarmLaterLollipop();
}
else {
// Code for older versions
alarmBeforeLollipop();
}
}
@TargetApi(Build.VERSION_CODES.M)
private void alarmLaterLollipop(){
logAlarm(targetTime, pendingIntent, intent, "Lollipop");
alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(targetTime, pendingIntent),pendingIntent);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void alarmBeforeLollipop(){
logAlarm(targetTime, pendingIntent, intent, "Kitkat");
alarmManager.setExact(AlarmManager.RTC_WAKEUP, targetTime, pendingIntent);
}