Advertisement
peachyontop

45ethysrthrth

Apr 5th, 2025
10
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.67 KB | None | 0 0
  1. from kivy.clock import Clock, mainthread
  2. from kivymd.app import MDApp
  3. from kivymd.uix.screen import Screen
  4. from plyer import gps, notification
  5. import requests
  6. import json
  7. from datetime import datetime
  8. from android.permissions import request_permissions, Permission, check_permission
  9.  
  10. class WeatherScreen(Screen):
  11. api_key = "YOUR_API_KEY" # Replace with your OpenWeatherMap API key
  12. gps_initialized = False
  13.  
  14. def on_enter(self):
  15. self.check_and_request_permissions()
  16.  
  17. def check_and_request_permissions(self):
  18. required_permissions = [Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION]
  19. if not all(check_permission(perm) for perm in required_permissions):
  20. request_permissions(required_permissions, self.permission_callback)
  21. else:
  22. self.start_gps()
  23.  
  24. def permission_callback(self, permissions, grants):
  25. if all(grants.values()):
  26. self.start_gps()
  27. else:
  28. notification.notify(title="Permissions Required",
  29. message="Location permissions are needed to get weather data")
  30.  
  31. def start_gps(self):
  32. try:
  33. if not self.gps_initialized:
  34. gps.configure(on_location=self.on_location,
  35. on_status=self.on_status)
  36. self.gps_initialized = True
  37. gps.start(minTime=5000, minDistance=10)
  38. Clock.schedule_once(lambda dt: self.gps_fallback(), 15)
  39. except NotImplementedError:
  40. notification.notify(title="GPS Error", message="GPS not supported")
  41.  
  42. def gps_fallback(self):
  43. if self.ids.location_label.text == "Locating...":
  44. notification.notify(title="Location Error",
  45. message="Couldn't get location. Using last known position.")
  46. # Add fallback to last known location here
  47.  
  48. def on_status(self, stype, status):
  49. if status == 'provider-enabled':
  50. self.start_gps()
  51. elif status == 'provider-disabled':
  52. notification.notify(title="GPS Disabled",
  53. message="Please enable GPS for accurate location")
  54.  
  55. def on_location(self, **kwargs):
  56. lat = kwargs.get('lat')
  57. lon = kwargs.get('lon')
  58. if lat and lon:
  59. Clock.unschedule(self.gps_fallback)
  60. self.get_weather(lat, lon)
  61.  
  62. # Keep the rest of the existing methods (get_weather, update_ui, etc.) the same
  63. # ...
  64.  
  65. class WeatherApp(MDApp):
  66. def build(self):
  67. self.theme_cls.primary_palette = "Blue"
  68. return WeatherScreen()
  69.  
  70. if __name__ == '__main__':
  71. WeatherApp().run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement