You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

适配min SDK 16:ArrayList.sort与AlarmManager兼容问题求助

适配minSDK16的解决方案

一、解决ArrayList.sort() API24依赖问题

ArrayList.sort()是API24才新增的方法,脱糖对这类默认方法的支持有限,直接换成兼容API1+的Collections.sort()即可:

  • 带比较器的排序:把list.sort(yourComparator)替换为Collections.sort(list, yourComparator)
  • 自然排序(元素实现Comparable):把list.sort()替换为Collections.sort(list)

该方法从Android API1就存在,完全覆盖minSDK16需求,无需依赖脱糖即可正常运行。

二、解决NotificationManager.createNotificationChannel() API26依赖问题

通知渠道是Android 8.0(API26)才引入的特性,低于该版本的系统不支持此功能,直接做版本判断即可:

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 仅在API26及以上系统创建通知渠道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(
        "your_channel_id",
        "你的渠道名称",
        NotificationManager.IMPORTANCE_DEFAULT
    );
    notificationManager.createNotificationChannel(channel);
}
// 后续创建通知的逻辑不变,API26以下系统会自动忽略渠道参数

三、AlarmManager适配API16+的注意事项

7.1.1(API25)平板上AlarmManager功能异常,多是不同API版本的调度行为差异导致,按以下逻辑适配:

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, YourAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
    this,
    requestCode,
    alarmIntent,
    // 适配API31+的flag要求
    Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ? 
        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE : 
        PendingIntent.FLAG_UPDATE_CURRENT
);

long triggerTime = System.currentTimeMillis() + 60 * 1000; // 示例:1分钟后触发

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    // API23+:Doze模式下也能触发的精确调度
    alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    // API19-API22:精确调度(API19后set()变为非精确)
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
} else {
    // API16-API18:直接用set()即可保证精确
    alarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
}

额外补充

  • 重复闹钟适配:API19后需用setInexactRepeating();若要精确重复,API23+需在广播接收后重新调用setExactAndAllowWhileIdle()(系统限制了精确重复闹钟的频率)。

内容的提问来源于stack exchange,提问作者Chris Damianidis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 03:45:05