Android13中Kivy+Plyer通知报错:需指定FLAG_IMMUTABLE/MUTABLE
问题描述
使用Plyer实现通知功能的Kivy代码在Windows及低版本Android运行正常,但在Android 13上抛出以下错误:
JVM exception occurred : org.test.notify : 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
用户提供的代码如下:
from kivy.app import App from kivy.lang import Builder from kivy.utils import platform from plyer import notification from kivy.uix.boxlayout import BoxLayout from kivy.clock import Clock from kivy.properties import DictProperty from kivy.uix.label import Label Builder.load_string(""" <NotificationDemo>: BoxLayout: Label: id: notification_text text: 'Hi user' font_size:50 """) a=0 class NotificationDemo(BoxLayout): kwargs = DictProperty() def update(self,dt): global a try: a = a + 1 sms = str(a) self.ids.notification_text.text = sms notification.notify(title='hello' , message=sms) except Exception as error: self.ids.notification_text.text = str(error) class ServiceApp(App): def build(self): fdir = NotificationDemo() Clock.schedule_interval(fdir.update, 6) return fdir def on_pause(self): return True if __name__ == '__main__': ServiceApp().run()
解决方案
1. 优先升级Plyer版本
这个错误源于Android 13(API 31+)要求创建PendingIntent时必须指定FLAG_IMMUTABLE或FLAG_MUTABLE标记,旧版本Plyer未适配该规则。直接升级到Plyer 2.1.0及以上版本即可,官方已修复该适配问题,无需修改原有代码。
2. 修改buildozer.spec配置(升级Plyer无效时)
若升级Plyer后仍存在问题,可在buildozer.spec中做以下配置:
- 确保目标API版本为31或更高:
android.api = 33 - 添加Android 13必需的通知权限:
android.permissions = POST_NOTIFICATIONS - 强制指定依赖的Plyer版本:
requirements = python3,kivy,plyer>=2.1.0
3. 是否需要使用服务?
不需要额外启用Android服务。当前报错是Plyer对Android 13的适配问题,和后台运行需求无关。只有当你的应用需要在后台持续发送通知时,才需要考虑使用Android服务,但这并非解决当前报错的必要操作。
内容的提问来源于stack exchange,提问作者Fathi

