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

KivyMD应用集成通知遇PendingIntent错误(Android API33)

KivyMD应用通知功能适配Android 31+的解决方案

问题背景

为KivyMD应用添加通知功能时,先后遇到两个错误:

  1. 初始错误:
AttributeError: type object 'notification.org.notificator.R$drawable' has no attribute 'icon'.

通过在buildozer.spec的requirements中添加plyer的master分支解决了上述问题,但出现新错误:

JVM exception occurred: org.test.xon: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent. Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles. java.lang.IllegalArgumentException

当前环境配置(Google Colab):

sudo apt install -y git zip unzip openjdk-17-jdk python3-pip autoconf libtool pkg-config zlib1g-dev libncurses5-dev libncursesw5-dev libtinfo5 cmake libffi-dev libssl-dev
pip3 install --upgrade Cython==0.29.19
pip3 install --upgrade buildozer
buildozer init

buildozer.spec关键配置:

android.api = 33
requirements = python3,kivy==2.1.0,kivymd==1.0.2,sdl2_ttf==2.0.15,pillow,requests,schedule,urllib3,charset_normalizer,idna,kaki,kivy_garden.graph,https://github.com/kivy/plyer/archive/refs/heads/master.zip

解决方案

该错误源于Android 12(API 31)及以上版本要求创建PendingIntent时必须指定FLAG_IMMUTABLE或FLAG_MUTABLE标记,当前使用的plyer master分支通知模块未处理该逻辑,可按以下步骤修复:

步骤1:修改plyer的Android通知实现代码

  1. 拉取plyer master分支源码:
git clone https://github.com/kivy/plyer.git
  1. 找到并修改plyer/platforms/android/notificator.py文件:
    • 在文件顶部添加导入语句:
      from android.os import Build
      from android.app import PendingIntent
      
    • 找到创建PendingIntent的代码块,替换为兼容API 31+的逻辑:
      # 替换原PendingIntent创建代码
      if Build.VERSION.SDK_INT >= Build.VERSION_CODES.S:
          pending_intent_flag = PendingIntent.FLAG_IMMUTABLE
      else:
          pending_intent_flag = 0
      
      pending_intent = PendingIntent.getActivity(
          PythonActivity.mActivity, 0, intent, pending_intent_flag
      )
      
  2. 将修改后的plyer源码打包为zip:
zip -r plyer-modified.zip plyer/

步骤2:更新buildozer.spec配置

将requirements中的plyer远程链接替换为本地修改后的zip文件(需先将zip上传至Colab环境),示例:

requirements = python3,kivy==2.1.0,kivymd==1.0.2,sdl2_ttf==2.0.15,pillow,requests,schedule,urllib3,charset_normalizer,idna,kaki,kivy_garden.graph,./plyer-modified.zip

替代方案:降低Android API版本(不推荐)

若暂时不想修改源码,可将buildozer.spec中的android.api改为30,绕过API 31+的PendingIntent标记要求,但此方法不符合最新Android应用上架规范:

android.api = 30

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:15:44