Every android app I build on kivy with buildozer restarts itself after being in the background. Even if I slide down the notifications when on the app the app restarts.
I tried finding documentation about this issue but didn't find anything.
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
import time
Builder.load_string('''
<CameraClick>:
orientation: 'vertical'
Camera:
id: camera
resolution: (640, 480)
play: False
ToggleButton:
text: 'Play'
on_press: camera.play = not camera.play
size_hint_y: None
height: '48dp'
Button:
text: 'Capture'
size_hint_y: None
height: '48dp'
on_press: root.capture()
''')
class CameraClick(BoxLayout):
def capture(self):
'''
Function to capture the images and give them the names
according to their captured time and date.
'''
camera = self.ids['camera']
timestr = time.strftime("%Y%m%d_%H%M%S")
camera.export_to_png("IMG_{}.png".format(timestr))
print("Captured")
class TestCamera(App):
def build(self):
return CameraClick()
TestCamera().run()
This is the app I'm trying to run, with a default buildozer.spec only adding opencv for the camera.
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
import time
Builder.load_string('''
<CameraClick>:
orientation: 'vertical'
Camera:
id: camera
resolution: (640, 480)
play: False
ToggleButton:
text: 'Play'
on_press: camera.play = not camera.play
size_hint_y: None
height: '48dp'
Button:
text: 'Capture'
size_hint_y: None
height: '48dp'
on_press: root.capture()
''')
class CameraClick(BoxLayout):
def capture(self):
'''
Function to capture the images and give them the names
according to their captured time and date.
'''
camera = self.ids['camera']
timestr = time.strftime("%Y%m%d_%H%M%S")
camera.export_to_png("IMG_{}.png".format(timestr))
print("Captured")
class TestCamera(App):
def build(self):
return CameraClick()
def on_pause(self):
return True
TestCamera().run()
Changing the on_pause method solves it.
Related
i'm working on a qr code scanner using kivy zbarcam, I managed to make it work but the problem is the camera initializes right away and does not release the camera after leaving the screen. I tried zbarcam.stop() and root.ids.zbarcam_id.ids.xcamera.play=False but what it does is just unscheduling and doesn't really release the use of camera. I tried to build this in buildozer but it's so slow since the camera is using a lot of memory even when not in use.
Can somebody know what is the workaround on this?
This is my code:
from kivy.lang.builder import Builder
from kivy.uix.screenmanager import Screen
from kivy.clock import Clock
from kivymd.app import MDApp
class QRScreen(Screen):
pass
class LoginScreen(Screen):
pass
class ScannerScreen(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
Clock.schedule_once(self._after_init)
# self.ids.zbarcam_id.ids.xcamera.play=True
def _after_init(self, dt):
"""
Binds `ZBarCam.on_symbols()` event.
"""
zbarcam = self.ids.zbarcam_id
zbarcam.bind(symbols=self.on_symbols)
def on_symbols(self, zbarcam, symbols):
"""
Loads the first symbol data to the `QRFoundScreen.data_property`.
"""
# going from symbols found to no symbols found state would also
# trigger `on_symbols`
if not symbols:
return
symbol = symbols[0]
data = symbol.data.decode('utf8')
print(data)
self.manager.get_screen('qr').ids.data.text= data
self.manager.transition.direction = 'left'
self.manager.current = 'qr'
def on_leave(self):
zbarcam = self.ids.zbarcam_id
zbarcam.stop()
class DemoApp(MDApp):
def build(self):
# screen =Screen()
self.title='Demeter'
self.theme_cls.theme_style = "Dark"
self.theme_cls.primary_palette = "DeepPurple"
self.help = Builder.load_file('main.kv')
return self.help
DemoApp().run()
kv file:
#:import ZBarCam kivy_garden.zbarcam.ZBarCam
ScreenManager:
LoginScreen:
ScannerScreen:
QRScreen:
<LoginScreen>:
name: "login"
MDFlatButton:
text:'release'
on_press:
root.manager.current = 'scanner'
root.manager.transition.direction = "right"
<ScannerScreen>:
name: 'scanner'
ZBarCam:
id: zbarcam_id
play: False
MDFlatButton:
id: iyu
text:'release'
on_press:
root.ids.zbarcam_id.ids.xcamera.play=False
MDFlatButton:
id: ads
text:'replay'
pos_hint: {"center_x": 0.5, "center_y": 0.95}
on_press:
root.ids.zbarcam_id.ids.xcamera.play=True
<QRScreen>:
name: 'qr'
MDIconButton:
icon:'arrow-left'
pos_hint: {'center_x':0.1,'center_y':0.95}
on_press:
root.manager.current = 'scanner'
root.manager.transition.direction = "right"
MDLabel:
id:data
text: "asdgasda"
pos_hint: {'center_y':0.5}
theme_text_color: "Custom"
text_color: 0, 1, 0, 1
I was having the same problem and finally found the solution (based on this)
In my case I initate ZBarCam in the .py file instead of .kv (see example).
To actually close the camera, you can call the following:zbarcam.ids['xcamera']._camera._device.release() in your on_leave() function.
If you initiate/manage ZBarCam in the .kv, I think that the equivalent would be something like: root.ids.zbarcam.ids.xcamera._camera._device.release()
If compiled with buildzoner for Android, I have to use self.zbarcam.ids['xcamera']._camera = None instead
I have the same error, I already install garden, kivy-garden, kivy, kivymd, pyzbar, and all the requriments in the buildozer.spec file, but when I run it, the log said ModuleNotFoundError: No module named 'kivy_garden.zbarcam', I have being trying a lot of solutions in other requriments, but any of that works.
Framework: I am talking about an Android app written in Python 2.7 and packaged with Builtdozer
I have a Builder inside the app with a button
Builder.load_string('''
FloatLayout:
orientation: 'horizontal'
Button:
text: str(root.name)
font_size: '20sp'
pos_hint: {'x':.0, 'y':.3}
size_hint: .4, .8
''')
I want to create a function, change_name, that, if I press the above button, opens the android keyboard to accept an user raw_input
The raw_input provided by the user has to replace the text of the above button.
What I thought is:
1) Create a variable name = StringProperty('Me')
2) Create a function:
def change_name(self):
self.name = raw_input()
3) Call the function inside my button with a on_release
Builder.load_string('''
FloatLayout:
orientation: 'horizontal'
Button:
text: str(root.name)
font_size: '20sp'
pos_hint: {'x':.0, 'y':.3}
size_hint: .4, .8
on_release: root.change_name()
''')
It is correct? Because actually, running the app on Ubuntu, I am trying to click on the button but the app does not ask for an input (it seems blocked).
As a consequence I believe it will not work also on Android.
Could you please help me understanding where am I wrong?
raw_input allows to get input from stdin (terminal). On Android you will not have the terminal available. In addition, raw_input is blocking, this causes the main event loop of your app to be freeze and will cause your app to stop responding.
You shouldn't use raw_input but Kivy's own methods.
On the other hand, you want to make your button editable (as if it were a TextInput). You can create your own custom Button class or use WindowBase.request_keyboard() to request the keyboard manually. However, you can do a little trick by hiding a TextInput and use it to enter the text:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput
kv_text= ('''
<MyWidget>:
FloatLayout:
orientation: 'horizontal'
Button:
text: 'Hello'
font_size: '20sp'
pos_hint: {'x':.0, 'y':.3}
size_hint: .4, .8
on_release: root.change_name(self)
Button:
text: 'World'
font_size: '20sp'
pos_hint: {'x':0.6, 'y':.3}
size_hint: .4, 0.8
on_release: root.change_name(self)
''')
class MyWidget(FloatLayout):
def __init__(self, **kwargs):
super(MyWidget, self).__init__(**kwargs)
self.hide_input = TextInput(size_hint=(None, None),
size = (0, 0),
multiline = False)
self.hide_input_bind = None
def change_name(self, instance):
if self.hide_input_bind:
self.hide_input.unbind_uid('text', self.hide_input_bind)
self.hide_input.text = instance.text
self.hide_input.focus = True
self.hide_input_bind = self.hide_input.fbind('text', self._update_text, instance)
def _update_text(self, button, instance, value):
button.text = value
class MyKivyApp(App):
def build(self):
return MyWidget()
def main():
Builder.load_string(kv_text)
app = MyKivyApp()
app.run()
if __name__ == '__main__':
main()
App working on Android (Kivy Launcher):
I want my Kivy app to have multiple ListView instances. I'm stuck when it comes to assigning different properties, especially callbacks. The following code illustrates my problem:
from kivy.app import App
from kivy.uix.listview import ListItemButton
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
Builder.load_string('''
#: import ListAdapter kivy.adapters.listadapter.ListAdapter
#: import ListItemButton kivy.uix.listview.ListItemButton
<smRoot>:
Screen1:
Screen2:
<ListItemButton>:
on_press: app.callback1(self)
height: dp(25)
size_hint: (1,.1)
<Screen1>:
name:'screen1'
BoxLayout:
orientation: 'vertical'
Label:
text: 'Screen1'
size_hint_y: .1
ListView:
id:lstScreen1
adapter:
ListAdapter(data=[{'text':'item1'},{'text':'item2'},{'text':'item3'}],
args_converter=lambda row_index, rec: {'text': rec['text']},
cls=ListItemButton,
selection_mode='single',
allow_empty_selection=False)
Button:
text: 'Switch Screen'
size_hint_y: .1
on_press: root.manager.current = 'screen2'
<ListItemButton>:
on_press: app.callback2(self)
height: dp(25)
size_hint: (1,.1)
<Screen2>:
name:'screen2'
BoxLayout:
orientation: 'vertical'
Label:
text: 'Screen2'
size_hint_y: .1
ListView:
id:lstScreen2
adapter:
ListAdapter(data=[{'text':'item1'},{'text':'item2'},{'text':'item3'}],
args_converter=lambda row_index, rec: {'text': rec['text']},
cls=ListItemButton,
selection_mode='single',
allow_empty_selection=False)
Button:
text: 'Switch Screen'
size_hint_y: .1
on_press: root.manager.current = 'screen1'
''')
class smRoot(ScreenManager):
pass
class Screen1(Screen):
MyButt = ListItemButton
pass
class Screen2(Screen):
pass
class myApp(App):
def build(self):
smroot = smRoot()
return smroot
def callback1(self, btn_instance):
index = btn_instance.index
print 'From Screen 1: ' + str(index)
def callback2(self, btn_instance):
index = btn_instance.index
print 'From Screen 2: ' + str(index)
myApp().run()
Here, I want each of the ListView instances on Screens 1 and 2 to have separate callbacks. But when I click on either screen, the output is the same, like so:
From Screen 2: 0
From Screen 1: 0
Ideally, I was hoping to implement something like a Dynamic Class. But when I tried something like this:
<MyButt#ListItemButton>:
#on_press: app.callback1(self)
height: dp(25)
size_hint: (1,.1)
<Screen1>:
name:'screen1'
MyButt:
on_press: app.callback1(self)
BoxLayout:
orientation: 'vertical'
Label:
text: 'Screen1'
size_hint_y: .1
ListView:
id:lstScreen1
adapter:
ListAdapter(data=[{'text':'item1'},{'text':'item2'},{'text':'item3'}],
args_converter=lambda row_index, rec: {'text': rec['text']},
cls=MyButt,
selection_mode='single',
allow_empty_selection=False)
I get a NameError: name 'MyButt' is not defined error. As far as I can tell, I've adhered to the same syntax in the documentation example linked above, so I'm confused.
I haven't tried creating a custom class in Python, but I would rather keep the UI elements separate in the .kv code (If I'm not mistaken, isn't that the basic idea behind kv?).
Any help/pointers/suggestions in this regard would be much appreciated.
You can't use a widget class from the python side (after ":") in kv without importing it, but since MyButt is not defined in any module, being a dynamic class (defined in pure kv) you can use Factory to use it.
first, import Factory at the top of your kv file.
#:import Factory kivy.factory.Factory
then change
ListView:
id:lstScreen1
adapter:
ListAdapter(data=[{'text':'item1'},{'text':'item2'},{'text':'item3'}],
args_converter=lambda row_index, rec: {'text': rec['text']},
cls=MyButt,
to
ListView:
id:lstScreen1
adapter:
ListAdapter(data=[{'text':'item1'},{'text':'item2'},{'text':'item3'}],
args_converter=lambda row_index, rec: {'text': rec['text']},
cls=Factory.MyButt,
Working with Kivy ActionBar, and i've successfully created a Search widget. The only problem is there is a lot of open space left in the ActionBar once I add the Search input.
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.lang import Builder
Builder.load_string("""
<RootWidget>:
ActionBar:
background_color: .5, .7, .6, 1
size_hint_y: .10
pos_hint: {'top':1}
ActionView:
ActionPrevious:
with_previous: False
SearchBar:
size_hint_x: 1
size_hint_y: .5
pos_hint: {'x': 0, 'center_y':.5}
on_text_validate: searchbutt.trigger_action()
ActionButton:
icon: "search.png"
size_hint_x: None
size_hint_y: None
size: (30,30)
pos_hint: {'x': .3, 'center_y': .5}
id: searchbutt
ActionOverflow:
ActionButton:
text: 'Btn1'
ActionButton:
text: 'Btn2'
ActionButton:
text: 'Btn3'
""")
class RootWidget(BoxLayout):
def __init__(self, *args, **kwargs):
super(RootWidget, self).__init__(*args, **kwargs)
pass
class SearchBar(TextInput, ActionItem):
def __init__(self, *args, **kwargs):
super(SearchBar, self).__init__(*args, **kwargs)
self.hint_text='Enter Location'
def search(self):
request = self.text
return str(request)
class VerticalPanes(BoxLayout):
orientation= 'vertical'
pass
class HorizontalPanes(BoxLayout):
pass
class EventScreen(App):
def build(self):
return RootWidget()
if __name__ == "__main__":
EventScreen().run()
Here is my file code, if you run it and resize the window then you can see the search bar shrinks until it is almost useless, yet empty space following the app icon is plentiful.
Also, if you see any general parts I can improve in my code/technique, lemme know.
PS: search.png is just a magnifying glass icon
ended up figuring it out. here is the code i'm going with:
<RootWidget>:
ActionBar:
background_color: .5, .7, .6, 1
size_hint_y: .10
pos_hint: {'top':1}
ActionView:
SearchBar:
size_hint_x: 1.7
size_hint_y: .5
pos_hint: {'x': 0, 'center_y':.5}
on_text_validate: searchbutt.trigger_action()
ActionButton:
text: 'Map'
ActionPrevious:
with_previous: False
ActionOverflow:
ActionButton:
text: 'Filters'
ActionButton:
text: 'Settings'
Figured out i just had to move the position of ActionPrevious in the kv lang code.
I have created a two button code for a simple Kivy app, but on clicking the button, it is unable to run a method.
When I click on 'Check in' button, it says AttributeError: 'Button' object has no attribute 'login'
Here is my code. I want to print a message on clicking button.
from kivy.app import App
from kivy.lang import Builder
button1 = '''
BoxLayout:
Button:
text: 'Check In'
height: "40dp"
on_press: login()
size_hint: None, None
pos_hint: {'center_x': .1, 'center_y': .1}
canvas.before:
PushMatrix
Rotate:
angle: 0
origin: self.center
canvas.after:
PopMatrix
Button:
text: 'SOS'
size_hint: None, None
pos_hint: {'center_x': .1, 'center_y': .1}
canvas.before:
PushMatrix
Rotate:
angle: 0
origin: self.center
canvas.after:
PopMatrix
'''
class RotationApp(App):
def build(self):
return Builder.load_string(button1)
def login(self):
print("Click the goddamn button")
RotationApp().run()
The button doesn't have a reference to the login method - as far as it's concerned that's just some random name that could have come from anywhere.
Since login is a method of your app class, you need a reference to the running app, which luckily kv language already provides with the app keyword. That means you should replace login with app.login.
You can also get a reference to the app in pure python via App.get_running_app(), which is in fact what the app keyword does behind the scenes.