android - Kivy 和 android 通知

标签 android python python-2.7 kivy

我正在尝试在我的 kivy 应用程序中使用 android 通知,但我遇到了问题。

起初我尝试使用 plyer,但它不起作用(应用程序崩溃)。所以我阅读了一些文章并查看了一些示例并尝试使用 jnius 自己完成并制作了这个简单的应用程序:

from kivy.app import App
from kivy.uix.button import Button

from jnius import autoclass

def notify(*args):
    AndroidString = autoclass('java.lang.String')
    PythonActivity = autoclass('org.kivy.android.PythonActivity')
    NotificationBuilder = autoclass('android.app.Notification$Builder')
    Drawable = autoclass('org.test.notify.R$drawable')
    icon = Drawable.icon
    notification_builder = NotificationBuilder(PythonActivity.mActivity)
    notification_builder.setContentTitle(AndroidString('Title'.encode('utf-8')))
    notification_builder.setContentText(AndroidString('Message'.encode('utf-8')))
    notification_builder.setSmallIcon(icon)
    notification_builder.setAutoCancel(True)
    notification_service = PythonActivity.mActivity.getSystemService(PythonActivity.NOTIFICATION_SERVICE)
    notification_service.notify(0,notification_builder.build())

class NotifyApp(App):
    def build(self):
        return Button(text="notify", on_press=notify)

if __name__ == '__main__':
    NotifyApp().run()

但是它不工作并且也崩溃了。我不明白为什么,因为它与 this example 中的相同或 this example但我刚刚将 org.renpy.android 更改为 org.kivy.android 因为 renpy 已被弃用(但是 org.renpy.android 没有任何变化)。

据我了解,问题在于:

notification_service = PythonActivity.mActivity.getSystemService(PythonActivity.NOTIFICATION_SERVICE)

因为我已经在 notify() 函数中测试了没有最后两行的这段代码并且它有效(但当然什么都不做)。

在 buildozer adb 日志中我可以看到这个错误:

10-15 16:57:00.432 22091 22112 F art     : art/runtime/java_vm_ext.cc:410] JNI DETECTED ERROR IN APPLICATION: static jfieldID 0x6fc46968 not valid for class java.lang.Class<org.kivy.android.PythonActivity>

我不擅长 Java,但在 plyer 和我发现的所有示例中都使用了相同的代码,似乎它适用于除我之外的所有人。

最佳答案

我找到了解决方案 here .我只需要使用上下文。所以工作代码看起来像这样:

Context = autoclass('android.content.Context')
notification_service = PythonActivity.mActivity.getSystemService(Context.NOTIFICATION_SERVICE)

希望对遇到同样问题的人有所帮助。

关于android - Kivy 和 android 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46760144/

相关文章:

android - 将 Stack Widget 的内容转换为图像

python - 当我从 CSV 中读取 Pandas 系列时,它正在将其转换为 DataFrame 吗?

python - 连接/附加不同大小的多个垂直数组

csv - Pandas read_csv 和 UTF-16

python - 如何从尽可能快运行的 CherryPy BackgroundTask 返回数据

在 Activity 中单击后退按钮时 Android Studio 运行命令

android - Firebase 动态链接处理了两次

android - 应用仅在 Android 5.0 上崩溃并出现 VerifyError

Python 脚本在第一次迭代后中断

用于运行 docker 的 Python 脚本