KIVY在手机休眠模式下不更新UI

0 投票
1 回答
636 浏览
提问于 2025-04-18 16:11

我又在尝试使用kivy的GPS示例,链接在这里:https://github.com/kivy/plyer/blob/master/examples/gps/main.py。但是当我按下开始按钮后,把手机放到睡眠模式(屏幕关闭)时,就出现了问题。过了一段时间我再打开屏幕和应用,看到的只是一个卡住的界面,因为在待机模式下标签无法更新。我该怎么解决这个问题呢?我希望即使手机处于睡眠模式,也能更新标签。

from kivy.lang import Builder
from plyer import gps
from kivy.app import App
from kivy.properties import StringProperty
from kivy.clock import Clock

kv = '''
BoxLayout:
    orientation: 'vertical'

    Label:
        text: app.gps_location

    Label:
        text: app.gps_status

    BoxLayout:
        size_hint_y: None
        height: '48dp'
        padding: '4dp'

        ToggleButton:
            text: 'Start' if self.state == 'normal' else 'Stop'
            on_state: app.gps.start() if self.state == 'down' else app.gps.stop()
'''


def mainthread(func):
    # This method is now part of Kivy 1.8.0. When it's released, remove it.
    def delayed_func(*args, **kwargs):
        def callback_func(dt):
            func(*args, **kwargs)
        Clock.schedule_once(callback_func, 0)
    return delayed_func


class GpsTest(App):

    def on_pause(self):
      # Here you can save data if needed
      return True

    def on_resume(self):
      # Here you can check if any data needs replacing (usually nothing)
      pass

    gps_location = StringProperty()
    gps_status = StringProperty('Click Start to get GPS location updates')

    def build(self):
        self.gps = gps
        try:
            self.gps.configure(on_location=self.on_location,
                    on_status=self.on_status)
        except NotImplementedError:
            import traceback; traceback.print_exc()
            self.gps_status = 'GPS is not implemented for your platform'

        return Builder.load_string(kv)

    @mainthread
    def on_location(self, **kwargs):
        self.gps_location = '\n'.join([
            '{}={}'.format(k, v) for k, v in kwargs.items()])

    @mainthread
    def on_status(self, stype, status):
        self.gps_status = 'type={}\n{}'.format(stype, status)

if __name__ == '__main__':
    GpsTest().run()

1 个回答

0

你不能保证应用在睡眠模式下会继续运行,所以这样做可能不是个好主意。更好的方法是使用安卓服务,这在python-for-android中是可以实现的。这里这里找到。

你可以在服务中处理GPS相关的内容,并在应用的on_resume和/或on_start时进行同步。

撰写回答