Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from kivy.clock import Clock, mainthread
- from kivymd.app import MDApp
- from kivymd.uix.screen import Screen
- from plyer import gps, notification
- import requests
- import json
- from datetime import datetime
- from android.permissions import request_permissions, Permission, check_permission
- class WeatherScreen(Screen):
- api_key = "YOUR_API_KEY" # Replace with your OpenWeatherMap API key
- gps_initialized = False
- def on_enter(self):
- self.check_and_request_permissions()
- def check_and_request_permissions(self):
- required_permissions = [Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION]
- if not all(check_permission(perm) for perm in required_permissions):
- request_permissions(required_permissions, self.permission_callback)
- else:
- self.start_gps()
- def permission_callback(self, permissions, grants):
- if all(grants.values()):
- self.start_gps()
- else:
- notification.notify(title="Permissions Required",
- message="Location permissions are needed to get weather data")
- def start_gps(self):
- try:
- if not self.gps_initialized:
- gps.configure(on_location=self.on_location,
- on_status=self.on_status)
- self.gps_initialized = True
- gps.start(minTime=5000, minDistance=10)
- Clock.schedule_once(lambda dt: self.gps_fallback(), 15)
- except NotImplementedError:
- notification.notify(title="GPS Error", message="GPS not supported")
- def gps_fallback(self):
- if self.ids.location_label.text == "Locating...":
- notification.notify(title="Location Error",
- message="Couldn't get location. Using last known position.")
- # Add fallback to last known location here
- def on_status(self, stype, status):
- if status == 'provider-enabled':
- self.start_gps()
- elif status == 'provider-disabled':
- notification.notify(title="GPS Disabled",
- message="Please enable GPS for accurate location")
- def on_location(self, **kwargs):
- lat = kwargs.get('lat')
- lon = kwargs.get('lon')
- if lat and lon:
- Clock.unschedule(self.gps_fallback)
- self.get_weather(lat, lon)
- # Keep the rest of the existing methods (get_weather, update_ui, etc.) the same
- # ...
- class WeatherApp(MDApp):
- def build(self):
- self.theme_cls.primary_palette = "Blue"
- return WeatherScreen()
- if __name__ == '__main__':
- WeatherApp().run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement