Search code examples
pythonandroidservicekivypyjnius

How to start service in python kivy on android in background mode?


I need a service for my app on android to receive message from server. Code of my app:

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
import sys
import socket
import time, subprocess
from kivy.uix.label import Label
from jnius import cast
from jnius import autoclass
from kivy.context import get_current_context
class MyApp(App):
    def build(self):
        fl = FloatLayout()
        try:
            service = autoclass('org.test.myapp.ServiceMyservice')                                                                  
            mActivity = autoclass('org.kivy.android.PythonActivity').mActivity
            service.start(mActivity, "")
        except Exception as error:
            fl.add_widget(Label(text=str(error), font_size=(30)))
    def on_stop(self):
        return True
if __name__ == '__main__':
    MyApp().run()

This code don't return any errors, but service doesn't start. Code of service:

import sys, socket, os, time, pickle
from jnius import autoclass, cast
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'example-78967.portmap.host'
port = 78967
s.connect((host,port))
s.send(('hello').encode('utf-8'))

I tried to start this code on smartphone and it worked, I received message. It means, that service does not start, and there aren't any errors.My service is located in the service/main.py. In section services in buildozer.spec I added:services = myservice:./service/main.py. And this I haven't tried to run it in the background yet. What I should do? I hope you help me.


Solution

  • on_stop method crashed the app, when I deleted it, my app has started works.