I want to build a simple Android app, like PushOver app, that has a TCP server and receive text messages which it logs and then send them as push notifications. This part is already done and working fine. But I want to receive messages even if the GUI app is closed. I know that this is possible because PushOver app does it ! I gues, I may need a service… but I don’t know how to make one, because this is my firs Andoroid app. As a development environment I use BeeWare(Toga/Briefcase) and Python on a Kubuntu machine. I activated the USB Debuging on the phone and I run the code directly on Android.
app.py
import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW
import threading, socket
Debug = True
# ----- Color codes ----------------------
RED = '33[31m'
GREEN = '33[32m'
YELLOW = '33[33m'
MAGENTA = '33[35m'
CYAN = '33[36m'
WHITE = '33[37m'
EXCEPT = '33[38;5;147m' # light purple
RESET = '33[0m'
EventColor = ['', GREEN, YELLOW, RED]
class TCPServer(threading.Thread):
def __init__(self, app):
super().__init__()
self.daemon = True
self.app = app
self.terminated = threading.Event()
self.start()
def Terminate(self):
if self.is_alive():
self.terminated.set()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as ESocket:
try:
ESocket.settimeout(0.2)
ESocket.connect(('localhost', 12345))
except: pass
self.join()
def run(self):
def HandleClient(Conn):
with Conn:
message = Conn.recv(1024).decode()
if not message: return
self.app.loop.call_soon_threadsafe(self.app.LogMessage, message)
#self.app.SendNotif(message)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as SSocket:
try:
SSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
SSocket.bind(('192.168.0.21', 12345))
SSocket.listen(10)
if Debug:
print(GREEN + 'TCP Server is listening on port 12345...' + RESET)
try:
while not self.terminated.is_set():
Conn, Addr = SSocket.accept()
if self.terminated.is_set():
Conn.close(); break
HandleClient(Conn)
except Exception as E1:
if Debug: print(RED + f'TCP Server exception (listen): {E1}' + RESET)
finally:
if Debug: print(YELLOW + 'TCP Server has stopped listening.' + RESET)
except Exception as E2:
if Debug: print(RED + f'TCP Server exception (setup): {E2}' + RESET)
class Application(toga.App):
def startup(self):
self.on_exit = self.exit_handler
self.main_window = toga.MainWindow(title=self.formal_name)
self.log = toga.MultilineTextInput(readonly=True, style=Pack(flex=1))
main_box = toga.Box(children=[self.log], style=Pack(direction=COLUMN, padding=10))
self.main_window.content = main_box
self.main_window.show()
self.tcp_server = TCPServer(self)
def exit_handler(self, app):
try:
self.tcp_server.Terminate()
finally:
return True
def LogMessage(self, message):
self.log.value += message + 'n'
def SendNotif(self, message):
self.main_window.info_dialog('New Message', message)
def main():
return Application()