1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
from kivy.lang import Builder
from plyer import gps
from kivy.app import App
from kivy.properties import StringProperty
from kivy.clock import mainthread
from kivy.utils import platform
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.start(1000, 0) if self.state == 'down' else \
app.stop()
'''
class GpsTest(App):
gps_location = StringProperty()
gps_status = StringProperty('Click Start to get GPS location updates')
def request_android_permissions(self):
"""
Since API 23, Android requires permission to be requested at runtime.
This function requests permission and handles the response via a
callback.
The request will produce a popup if permissions have not already been
been granted, otherwise it will do nothing.
"""
from android.permissions import request_permissions, Permission
def callback(permissions, results):
"""
Defines the callback to be fired when runtime permission
has been granted or denied. This is not strictly required,
but added for the sake of completeness.
"""
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], callback)
# # To request permissions without a callback, do:
# request_permissions([Permission.ACCESS_COARSE_LOCATION,
# Permission.ACCESS_FINE_LOCATION])
def build(self):
try:
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'
if platform == "android":
print("gps.py: Android detected. Requesting permissions")
self.request_android_permissions()
return Builder.load_string(kv)
def start(self, minTime, minDistance):
gps.start(minTime, minDistance)
def stop(self):
gps.stop()
@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)
def on_pause(self):
gps.stop()
return True
def on_resume(self):
gps.start(1000, 0)
pass
if __name__ == '__main__':
GpsTest().run()
|