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

Capacitor v4升级后本地通知触发应用崩溃问题求助

解决方案

1. 手动清除残留警报(快速临时修复)

由于新旧插件的通知管理机制不兼容,旧插件创建的警报无法被新插件的LocalNotifications.getPending()识别,可通过ADB命令直接清除应用的所有警报:

adb shell dumpsys alarm --cancel 你的应用包名

替换你的应用包名为实际包名(比如日志里的app),执行后重启应用即可释放被占用的AlarmManager名额。

2. 代码层面添加迁移清理(长效解决)

为避免用户升级应用后重复出现该问题,需在代码中添加一次迁移处理:

  • 借助Capacitor的Preferences插件标记是否已执行迁移。
  • 首次启动新版本时,通过自定义Capacitor插件调用Android原生API清除所有残留警报:
    1. 创建Android端插件逻辑:
      @CapacitorPlugin(name = "AlarmCleaner")
      public class AlarmCleanerPlugin extends Plugin {
          @PluginMethod()
          public void clearAllAlarms(PluginCall call) {
              AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
              // 清除新插件相关的警报
              Intent newIntent = new Intent(getContext(), com.capacitorjs.plugins.localnotifications.TimedNotificationPublisher.class);
              PendingIntent newPendingIntent = PendingIntent.getBroadcast(getContext(), 0, newIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_NO_CREATE);
              if (newPendingIntent != null) alarmManager.cancel(newPendingIntent);
              // 清除旧插件遗留的警报
              Intent oldIntent = new Intent(getContext(), com.ionicframework.nativeplugins.localnotifications.LocalNotificationsReceiver.class);
              PendingIntent oldPendingIntent = PendingIntent.getBroadcast(getContext(), 0, oldIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_NO_CREATE);
              if (oldPendingIntent != null) alarmManager.cancel(oldPendingIntent);
              call.resolve();
          }
      }
      
    2. 前端初始化时触发迁移:
      import { Preferences } from '@capacitor/preferences';
      import { AlarmCleaner } from './path-to-alarm-cleaner-plugin';
      
      async function migrateOldNotifications() {
          const { value } = await Preferences.get({ key: 'notifications_migrated' });
          if (!value) {
              await AlarmCleaner.clearAllAlarms();
              await Preferences.set({ key: 'notifications_migrated', value: 'true' });
          }
      }
      
      // 应用启动时调用
      migrateOldNotifications();
      

3. 排查代码逻辑避免重复创建

检查通知设置代码,确保不会重复添加相同通知:通过通知ID做唯一性校验,避免每次页面加载都调用schedule()而未检查是否已存在,防止警报堆积。


内容的提问来源于stack exchange,提问作者tesw axs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:40:19