'kivy app dont sending data in the background (when screen is off)
Kivy service app dont send any data to mysql when screen is off
Trying write simple app with kivy python which should run the service when you press the button. Service must track gps location (using plyer) and sending Name (from label) Lat Lon (from on_gps_location) and date from var datetime to mysql db. Its actualy working pretty well when you using app or switched it to another app. But when u turning off phone screen service dont stop cause i see the notification about service is running but no one new data dont sending anymore. Note: im testing it with difference phones, its actually working on any phones but not on my (HONOR 30i) Note2: When u select "traffic stat" on your phone it calls that your app spent for example 30mb when u using app and 0mb in background.
There my main.py code:
from kivy.app import App
from kivy.uix.button import Button
from kivy.config import Config
from plyer import gps
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
import mysql.connector
import android
from mysql.connector import errorcode
from datetime import datetime
from kivy.utils import platform
from kivy.clock import Clock
import time
from jnius import autoclass
from android import AndroidService
from kivy.storage.jsonstore import JsonStore
from threading import Thread
store = JsonStore('hello.json')
class MyApp(App):
def request_android_permissions(self):
from android.permissions import request_permissions, Permission
def callback(permissions, results):
if all([res for res in results]):
print('callback. All permissions granted.')
else:
print('callback. Some permissions refused.')
request_permissions([Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_BACKGROUND_LOCATION, Permission.WRITE_EXTERNAL_STORAGE], callback)
def build(self):
if platform == 'android':
print('Requesting permissions')
self.request_android_permissions()
print('App is running')
if len(store) == 0:
al = AnchorLayout()
bl = BoxLayout(orientation = 'vertical', size_hint=[None,None], size = [500,300])
self.lbl1 = Label(text = 'Put your name here')
bl.add_widget(self.lbl1)
self.txt1 = TextInput(text = '', multiline = False)
bl.add_widget(self.txt1)
bl.add_widget(Button(text = 'Start', on_press = self.btn_press_start))
al.add_widget(bl)
return al
else:
al = AnchorLayout()
bl = BoxLayout(orientation = 'vertical', size_hint = [None, None], size = [500,300])
self.lbl1 = Label(text = 'Hello ' + store.get('Name')['name'])
bl.add_widget(self.lbl1)
bl.add_widget(Button(text = 'Start', on_press = self.btn_press_start))
al.add_widget(bl)
return al
def btn_press_start(self, instance):
global name
if len(store) == 0:
if instance.text == 'Start':
if self.txt1.text != '':
self.lbl1.text = 'Hello ' + self.txt1.text
store.put('Name', name = self.txt1.text)
print('Beggin')
name = self.txt1.text
self.start_service()
instance.text = 'Stop'
else:
self.lbl1.text = 'Write smth there!'
else:
#gps.stop()
self.service.stop()
print('Service stop')
self.txt1.text = ''
instance.text = 'Start'
else:
if instance.text == 'Start':
name = store.get('Name')['name']
self.start_service()
instance.text = 'Stop'
else:
self.service.stop()
print('Service stop')
instance.text = 'Start'
def start_service(self):
self.service = AndroidService('Service example', 'service is running')
self.service.start(name)
if name == "main":
MyApp().run()
and my service/main.py code:
import os
from os import environ
from kivy.app import App
from kivy.uix.button import Button
from kivy.config import Config
from plyer import gps
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
import mysql.connector
import android
from mysql.connector import errorcode
from datetime import datetime
from kivy.utils import platform
from kivy.clock import Clock
import time
from jnius import autoclass
from android import AndroidService
print('SERVICE ON')
arg = environ.get('PYTHON_SERVICE_ARGUMENT', '')
def main():
gps.configure(on_location = on_gps_location)
print('Configure succes')
gps.start(minTime = 2000, minDistance = 0)
print('Going on')
time.sleep(10)
gps.stop()
print('BEFORE REPEAT')
config = {
'user': '', //I CLEAR THIS FIELDS//
'password': '',
'host': '',
'database': '',
'raise_on_warnings': True
}
db = mysql.connector.connect(**config)
cursor = db.cursor()
cur_time = datetime.now()
now = cur_time.strftime("%Y-%m-%d %H:%M:%S")
data_coord = {
'name' : arg,
'c1' : lat,
'c2' : lon,
'time': now,
}
add_coordinate = ("INSERT INTO //YOURDATABASE// (Name, Latitude, Longtitude, Date) VALUES (%(name)s, %(c1)s, %(c2)s, %(time)s)")
cursor.execute(add_coordinate, data_coord)
print('DATABASE UPDATE')
db.commit()
db.close()
def on_gps_location(**kwargs):
global lat
global lon
lat = kwargs['lat']
lon = kwargs['lon']
if __name__ == '__main__':
while True:
main()
time.sleep(20)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
