I'm trying to use android notifications in my kivy application and I'm having a problem.
At first I've tried to use plyer but it doesn't work (app just crashes). So I've read some articles and looked some examples and tried to do it myself using jnius and made this simple application:
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()
But it doesn't work and crashes too. I can't understand why because it's the same as in this example or this example but I've just changed org.renpy.android to org.kivy.android because renpy is deprecated (however with org.renpy.android nothing changes).
As far as I understand the problem is in the line:
notification_service = PythonActivity.mActivity.getSystemService(PythonActivity.NOTIFICATION_SERVICE)
Because I've tested this code without 2 last lines in notify() function and it works (but of course does nothing).
In buildozer adb log I can see this error:
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
I'm not good in Java but the same code is used in plyer and in all examples that I've found and it seems that it works for everyone except me.
解决方案
I have found the solution here. I just had to use Context. So work code looks like this:
Context = autoclass('android.content.Context')
notification_service = PythonActivity.mActivity.getSystemService(Context.NOTIFICATION_SERVICE)
I hope this helps those who encounter the same problem.