PRODUCTION - READY NOTIFICATION SERVICE for weather app, I want to build a minimal…
- User
PRODUCTION - READY NOTIFICATION SERVICE for weather app,
I want to build a minimal Notification Manager for my app in efficient, optimized, cleaner, robust and performant way without affecting battery and performance. Use Kotlin Coroutines, Workers, Koin, Jetpack Compose and material3 library, Flows, Jetpack datstore preferences, KotlinX date time, KotlinX serialization, and my Arrow for better error handling. Follow Clean Android Architecture guidelines, KISS, SOLID principles and DON'T OVER ENGINEER IT. Just create a simple implementation to test it then i will scale it slowly just create the foundation part first.
ON-GOING NOTIFICATION
- Create a persistent notification showing location name, temp, condition, and weather icon with status bar icon showing temp or icon. the notification and statusBar icon should be consistent. and add a toggle in settings to turnerd it on/off.
- If notification permission is not granted ask permission first, if denied multiple times go to noti-permission settings.
- Add option to expand to show more weather details like feels like, uv, humidity,wind, AQI. and update interval[30 min, 1hour, 3hours, 6hours] for updating weather by API calls in background.
- Add a test button below to test full real time preview of notification .so when users clicked , and it instantly shoes what real notification will look like. Add a option to select a notification for which location to show.
DAILY NOTIFICATION
- List all the weather for location to show notification.
- Add a time interval [ Hurly, Every 3/6 hours, Daily with Time, user can select ]
- Add a test button below to test full real time preview of notification .so when users clicked , and it instantly shoes what real notification will look like.
SEVERE WEATHER ALERTS
- Add a separate toggle in settings for both ongoing and daily notification for showing weather alerts. and add the condition for showing it like Precipitaion chances, heavy thunder storm, very cloudy.
Also, consider my domain models:
data class Weather( val id: Long = 0, val condition: Condition, val location: Location, val feelslike_c: Double, val feelslike_f: Double, val humidity: Int, val is_day: Int, val precip_in: Double, val precip_mm: Double, val pressure_in: Double, val pressure_mb: Double, val temp_c: Double, val temp_f: Double, val wind_kph: Double, val wind_mph: Double, val wind_dir: String, val wind_degree: Int, val vis_km: Double, val vis_miles: Double, val gust_kph: Double, val gust_mph: Double, val cloud: Int, val uv: Double, val lat: Double, val lon: Double, val located: Boolean, val air_quality: AirQuality, val dewpoint_c: Double, val dewpoint_f: Double, )
data class Condition( val code: Int, val icon: String, val text: String, )
data class Location( val country: String, val name: String, val region: String, val localtime: String, val localtimeEpoch: Int, val timezoneId: String,
) data class Alerts( val alert: List<Alert>)
data class Alert( val areas: String, val category: String, val certainty: String, val desc: String, val effective: String, val event: String, val expires: String, val headline: String, val instruction: String, val msgtype: String, val note: String, val severity: String, val urgency: String )
// usecases for domain layer is
class GetWeatherDBbyCityIdUseCase @Inject constructor( private val repository: WeatherRepository ) { suspend operator fun invoke(cityId: Long): WeatherResult<Weather?> { return repository.getWeatherByCityId(cityId) .map { entity -> entity?.mapEntityToWeather() } } }
class UpdateWeatherByIdUseCase( private val savedLocationRepository: WeatherRepository, ) { operator fun invoke(cityId: Long): Flow<WeatherResult> = flow { val result = savedLocationRepository .updateWeatherDataById(cityId) .map { entity -> entity.mapEntityToWeather() } emit(result) }.flowOn(Dispatchers.IO) }
// on both current and forecast data class AirQuality( val co: Double, val ukDefraIndex: Int, val no2: Double, val o3: Double, val pm10: Double, val pm25: Double, val so2: Double, val usEPAStandard: Int )
and Domain error // domain/error/WeatherDomainError.kt
sealed interface WeatherDomainError { data object Connectivity : WeatherDomainError data class LocationNotFound(val id: Long) : WeatherDomainError data class InvalidCoordinates(val lat: Double, val lon: Double) : WeatherDomainError data object Unauthorized : WeatherDomainError data class Unexpected(val debug: String? = null) : WeatherDomainError }
// Type alias for cleaner signatures typealias WeatherResult = Either<WeatherDomainError, T>
sealed interface WeatherUiError { data object Offline : WeatherUiError data object LocationNotFound : WeatherUiError data object InvalidLocation : WeatherUiError data object AuthorizationRequired : WeatherUiError data object Unknown : WeatherUiError data object LocationServicesDisabled : WeatherUiError data object NoSavedLocations : WeatherUiError
// For backup/restore errors data object NoLocationsToBackup : WeatherUiError data object EmptyBackupFile : WeatherUiError data object InvalidBackupData : WeatherUiError data object BackupFailed : WeatherUiError data object RestoreFailed : WeatherUiError companion object { fun fromDomainError(error: WeatherDomainError): WeatherUiError = when (error) { is WeatherDomainError.Connectivity -> Offline is WeatherDomainError.LocationNotFound -> LocationNotFound is WeatherDomainError.InvalidCoordinates -> InvalidLocation is WeatherDomainError.Unauthorized -> AuthorizationRequired is WeatherDomainError.Unexpected -> Unknown } fun fromBackupError(error: BackupError): WeatherUiError = when (error) { is BackupError.NoLocationsToBackup -> NoLocationsToBackup is BackupError.EmptyBackupFile -> EmptyBackupFile is BackupError.InvalidBackupData -> InvalidBackupData is BackupError.IOError, is BackupError.DatabaseError, is BackupError.SerializationError -> BackupFailed } } fun getErrorMessage(): String = when (this) { is Offline -> "No internet connection available" is LocationNotFound -> "Location could not be found" is InvalidLocation -> "Invalid location coordinates" is AuthorizationRequired -> "Authorization required" is Unknown -> "An unexpected error occurred" is NoLocationsToBackup -> "No locations to backup" is EmptyBackupFile -> "Backup file is empty" is InvalidBackupData -> "Invalid backup file format" is BackupFailed -> "Failed to create backup" is RestoreFailed -> "Failed to restore data" is LocationServicesDisabled -> "Please enable location services" is NoSavedLocations -> "No saved locations found" }}
Assistant
Notification Service for Weather App
I'll create a clean, minimal foundation for your notification service following your requirements. Let's break this down into components following Clean Architecture principles.
Project Structure
com.example.weather.notification/ ├── data/ │ ├── local/ │ ├── remote/ │ └── repository/ ├── domain/ │ ├── model/ │ ├── repository/ │ └── usecase/ └── presentation/ ├── components/ ├── viewmodel/ └── worker/1. Domain Layer
First, let's define the domain models and use cases for notifications.
Notification Models
// domain/model/Notification.kt data class NotificationSettings( val isOngoingNotificationEnabled: Boolean = false, val isDailyNotificationEnabled: Boolean = false, val isSevereAlertsEnabled: Boolean = false, val ongoingUpdateInterval: UpdateInterval = UpdateInterval.HOUR_1, val dailyNotificationTime: String = "08:00", // Default to 8 AM val dailyNotificationFrequency: DailyFrequency = DailyFrequency.DAILY, val selectedLocationId: Long? = null ) enum class UpdateInterval(val hours: Int) { MIN_30(0.5f), HOUR_1(1), HOUR_3(3), HOUR_6(6) } enum class DailyFrequency { HOURLY, EVERY_3_HOURS, EVERY_6_HOURS, DAILY } data class NotificationContent( val location: Location, val condition: Condition, val temp: Double, val feelsLike: Double, val humidity: Int, val wind: Double, val uv: Double, val airQuality: AirQuality, val isDay: Boolean )Notification Use Cases
// domain/usecase/notification/GetNotificationSettingsUseCase.kt class GetNotificationSettingsUseCase @Inject constructor( private val notificationRepository: NotificationRepository ) { operator fun invoke(): Flow<NotificationSettings> = notificationRepository.getNotificationSettings() } // domain/usecase/notification/UpdateNotificationSettingsUseCase.kt class UpdateNotificationSettingsUseCase @Inject constructor( private val notificationRepository: NotificationRepository ) { suspend operator fun invoke(settings: NotificationSettings): WeatherResult<Unit> = notificationRepository.updateNotificationSettings(settings) } // domain/usecase/notification/GetNotificationContentUseCase.kt class GetNotificationContentUseCase @Inject constructor( private val weatherRepository: WeatherRepository, private val notificationRepository: NotificationRepository ) { suspend operator fun invoke(locationId: Long): WeatherResult<NotificationContent> { return weatherRepository.getWeatherByCityId(locationId).map { weather -> weather?.let { NotificationContent( location = it.location, condition = it.condition, temp = it.temp_c, feelsLike = it.feelslike_c, humidity = it.humidity, wind = it.wind_kph, uv = it.uv, airQuality = it.air_quality, isDay = it.is_day == 1 ) } ?: throw WeatherDomainError.LocationNotFound(locationId) } } }2. Data Layer
Notification Repository Interface
// domain/repository/NotificationRepository.kt interface NotificationRepository { fun getNotificationSettings(): Flow<NotificationSettings> suspend fun updateNotificationSettings(settings: NotificationSettings): WeatherResult<Unit> suspend fun shouldShowSevereAlert(weather: Weather): Boolean }DataStore Implementation
// data/local/NotificationSettingsDataStore.kt class NotificationSettingsDataStore @Inject constructor( @ApplicationContext private val context: Context ) { companion object { private val Context.dataStore by preferencesDataStore(name = "notification_settings") private val IS_ONGOING_ENABLED = booleanPreferencesKey("is_ongoing_enabled") private val IS_DAILY_ENABLED = booleanPreferencesKey("is_daily_enabled") private val IS_SEVERE_ALERTS_ENABLED = booleanPreferencesKey("is_severe_alerts_enabled") private val ONGOING_UPDATE_INTERVAL = stringPreferencesKey("ongoing_update_interval") private val DAILY_NOTIFICATION_TIME = stringPreferencesKey("daily_notification_time") private val DAILY_NOTIFICATION_FREQUENCY = stringPreferencesKey("daily_notification_frequency") private val SELECTED_LOCATION_ID = longPreferencesKey("selected_location_id") } private val dataStore = context.dataStore fun getNotificationSettings(): Flow<NotificationSettings> = context.dataStore.data .map { preferences -> NotificationSettings( isOngoingNotificationEnabled = preferences[IS_ONGOING_ENABLED] ?: false, isDailyNotificationEnabled = preferences[IS_DAILY_ENABLED] ?: false, isSevereAlertsEnabled = preferences[IS_SEVERE_ALERTS_ENABLED] ?: false, ongoingUpdateInterval = try { UpdateInterval.valueOf(preferences[ONGOING_UPDATE_INTERVAL] ?: "HOUR_1") } catch (e: Exception) { UpdateInterval.HOUR_1 }, dailyNotificationTime = preferences[DAILY_NOTIFICATION_TIME] ?: "08:00", dailyNotificationFrequency = try { DailyFrequency.valueOf(preferences[DAILY_NOTIFICATION_FREQUENCY] ?: "DAILY") } catch (e: Exception) { DailyFrequency.DAILY }, selectedLocationId = preferences[SELECTED_LOCATION_ID] ) } suspend fun updateNotificationSettings(settings: NotificationSettings) { context.dataStore.edit { preferences -> preferences[IS_ONGOING_ENABLED] = settings.isOngoingNotificationEnabled preferences[IS_DAILY_ENABLED] = settings.isDailyNotificationEnabled preferences[IS_SEVERE_ALERTS_ENABLED] = settings.isSevereAlertsEnabled preferences[ONGOING_UPDATE_INTERVAL] = settings.ongoingUpdateInterval.name preferences[DAILY_NOTIFICATION_TIME] = settings.dailyNotificationTime preferences[DAILY_NOTIFICATION_FREQUENCY] = settings.dailyNotificationFrequency.name settings.selectedLocationId?.let { id -> preferences[SELECTED_LOCATION_ID] = id } } } }Notification Repository Implementation
// data/repository/NotificationRepositoryImpl.kt class NotificationRepositoryImpl @Inject constructor( private val settingsDataStore: NotificationSettingsDataStore, private val weatherRepository: WeatherRepository ) : NotificationRepository { override fun getNotificationSettings(): Flow<NotificationSettings> = settingsDataStore.getNotificationSettings() override suspend fun updateNotificationSettings(settings: NotificationSettings): WeatherResult<Unit> = Either.catch { settingsDataStore.updateNotificationSettings(settings) }.mapLeft { error -> WeatherDomainError.Unexpected(error.message) } override suspend fun shouldShowSevereAlert(weather: Weather): Boolean { // Implement your severe weather conditions logic here return with(weather) { // Example conditions - adjust based on your requirements condition.code in listOf(1063, 1069, 1072, 1150, 1153, 1168, 1171, 1180, 1183, 1186, 1189, 1192, 1195, 1198, 1201, 1204, 1207, 1240, 1243, 1246, 1249, 1252, 1255, 1258, 1261, 1264, 1273, 1276, 1279, 1282) || precip_mm > 5.0 || wind_kph > 30.0 || uv > 8.0 || air_quality.usEPAStandard > 3 } } }3. Presentation Layer
Notification Worker
// presentation/worker/NotificationWorker.kt class NotificationWorker @Inject constructor( @ApplicationContext private val context: Context, private val getNotificationContentUseCase: GetNotificationContentUseCase, private val getNotificationSettingsUseCase: GetNotificationSettingsUseCase, workerParams: WorkerParameters ) : CoroutineWorker(context, workerParams) { override suspend fun doWork(): Result { val settings = getNotificationSettingsUseCase().first() val locationId = settings.selectedLocationId ?: return Result.failure() return when (val result = getNotificationContentUseCase(locationId)) { is Either.Left -> Result.failure() is Either.Right -> { val content = result.value showNotification(content) Result.success() } } } private fun showNotification(content: NotificationContent) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationId = NOTIFICATION_ID val channelId = NOTIFICATION_CHANNEL_ID // Create notification channel if needed if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( channelId, "Weather Notifications", NotificationManager.IMPORTANCE_LOW ).apply { description = "Weather updates and alerts" setShowBadge(false) } notificationManager.createNotificationChannel(channel) } // Create the notification val notification = NotificationCompat.Builder(context, channelId) .setSmallIcon(getWeatherIcon(content.condition.code)) .setContentTitle("${content.location.name}, ${content.location.country}") .setContentText("${content.temp}°C, ${content.condition.text}") .setPriority(NotificationCompat.PRIORITY_LOW) .setOngoing(true) .setStyle( NotificationCompat.DecoratedCustomViewStyle().apply { setDecoratedCustomViewStyle() } ) .build() notificationManager.notify(notificationId, notification) } private fun getWeatherIcon(conditionCode: Int): Int { return when (conditionCode) { 1000 -> R.drawable.ic_sunny 1003 -> R.drawable.ic_partly_cloudy // Add more condition codes as needed else -> R.drawable.ic_cloudy } } companion object { private const val NOTIFICATION_ID = 1 private const val NOTIFICATION_CHANNEL_ID = "weather_notification_channel" } }Notification ViewModel
// presentation/viewmodel/NotificationViewModel.kt @HiltViewModel class NotificationViewModel @Inject constructor( private val getNotificationSettingsUseCase: GetNotificationSettingsUseCase, private val updateNotificationSettingsUseCase: UpdateNotificationSettingsUseCase, private val getNotificationContentUseCase: GetNotificationContentUseCase, private val workManager: WorkManager, private val notificationManager: NotificationManager ) : ViewModel() { private val _notificationSettings = MutableStateFlow(NotificationSettings()) val notificationSettings: StateFlow<NotificationSettings> = _notificationSettings private val _notificationContent = MutableStateFlow<NotificationContent?>(null) val notificationContent: StateFlow<NotificationContent?> = _notificationContent private val _uiState = MutableStateFlow<NotificationUiState>(NotificationUiState.Loading) val uiState: StateFlow<NotificationUiState> = _uiState init { loadSettings() } private fun loadSettings() { viewModelScope.launch { getNotificationSettingsUseCase() .catch { e -> _uiState.value = NotificationUiState.Error(WeatherUiError.Unknown) } .collect { settings -> _notificationSettings.value = settings _uiState.value = NotificationUiState.Success } } } fun updateSettings(settings: NotificationSettings) { viewModelScope.launch { updateNotificationSettingsUseCase(settings) .onLeft { error -> _uiState.value = NotificationUiState.Error(WeatherUiError.fromDomainError(error)) } .onRight { _notificationSettings.value = settings scheduleWorkers() } } } fun testNotification(locationId: Long) { viewModelScope.launch { when (val result = getNotificationContentUseCase(locationId)) { is Either.Left -> { _uiState.value = NotificationUiState.Error(WeatherUiError.fromDomainError(result.value)) } is Either.Right -> { _notificationContent.value = result.value showTestNotification(result.value) } } } } private fun showTestNotification(content: NotificationContent) { // Similar to NotificationWorker but for immediate preview } private fun scheduleWorkers() { val settings = _notificationSettings.value // Cancel existing workers workManager.cancelAllWork() // Schedule ongoing notification worker if enabled if (settings.isOngoingNotificationEnabled && settings.selectedLocationId != null) { val ongoingRequest = PeriodicWorkRequestBuilder<NotificationWorker>( settings.ongoingUpdateInterval.hours, TimeUnit.HOURS ).build() workManager.enqueueUniquePeriodicWork( "ongoing_notification_work", ExistingPeriodicWorkPolicy.REPLACE, ongoingRequest ) } // Schedule daily notification worker if enabled if (settings.isDailyNotificationEnabled && settings.selectedLocationId != null) { val dailyRequest = when (settings.dailyNotificationFrequency) { DailyFrequency.HOURLY -> PeriodicWorkRequestBuilder<NotificationWorker>( 1, TimeUnit.HOURS ).build() DailyFrequency.EVERY_3_HOURS -> PeriodicWorkRequestBuilder<NotificationWorker>( 3, TimeUnit.HOURS ).build() DailyFrequency.EVERY_6_HOURS -> PeriodicWorkRequestBuilder<NotificationWorker>( 6, TimeUnit.HOURS ).build() DailyFrequency.DAILY -> { val (hour, minute) = settings.dailyNotificationTime.split(":").map { it.toInt() } val now = Calendar.getInstance() val targetTime = Calendar.getInstance().apply { set(Calendar.HOUR_OF_DAY, hour) set(Calendar.MINUTE, minute) } if (targetTime.before(now)) { targetTime.add(Calendar.DATE, 1) } val delay = targetTime.timeInMillis - now.timeInMillis val initialDelay = delay.coerceAtLeast(15 * 60 * 1000) // Minimum 15 minutes PeriodicWorkRequestBuilder<NotificationWorker>( 24, TimeUnit.HOURS ).setInitialDelay(initialDelay, TimeUnit.MILLISECONDS).build() } } workManager.enqueueUniquePeriodicWork( "daily_notification_work", ExistingPeriodicWorkPolicy.REPLACE, dailyRequest ) } } fun checkNotificationPermission(): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { ContextCompat.checkSelfPermission( getApplication(), Manifest.permission.POST_NOTIFICATIONS ) == PackageManager.PERMISSION_GRANTED } else { true } } fun requestNotificationPermission(activity: Activity, requestCode: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { ActivityCompat.requestPermissions( activity, arrayOf(Manifest.permission.POST_NOTIFICATIONS), requestCode ) } } fun openNotificationSettings() { val intent = Intent().apply { action = Settings.ACTION_APP_NOTIFICATION_SETTINGS putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) flags = Intent.FLAG_ACTIVITY_NEW_TASK } context.startActivity(intent) } } sealed class NotificationUiState { object Loading : NotificationUiState() object Success : NotificationUiState() data class Error(val error: WeatherUiError) : NotificationUiState() }Notification Settings Screen
// presentation/components/NotificationSettingsScreen.kt @Composable fun NotificationSettingsScreen( viewModel: NotificationViewModel, onBackClick: () -> Unit ) { val settings by viewModel.notificationSettings.collectAsState() val uiState by viewModel.uiState.collectAsState() val context = LocalContext.current Scaffold( topBar = { TopAppBar( title = { Text("Notification Settings") }, navigationIcon = { IconButton(onClick = onBackClick) { Icon(Icons.Default.ArrowBack, contentDescription = "Back") } } ) } ) { padding -> when (uiState) { is NotificationUiState.Loading -> { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() } } is NotificationUiState.Error -> { val error = (uiState as NotificationUiState.Error).error ErrorScreen(error = error.getErrorMessage(), onRetry = { viewModel.loadSettings() }) } is NotificationUiState.Success -> { Column( modifier = Modifier .fillMaxSize() .padding(padding) .verticalScroll(rememberScrollState()) ) { // Ongoing Notification Section SectionHeader(title = "Ongoing Notification") SwitchSetting( title = "Enable Ongoing Notification", checked = settings.isOngoingNotificationEnabled, onCheckedChange = { enabled -> viewModel.updateSettings( settings.copy(isOngoingNotificationEnabled = enabled) ) } ) if (settings.isOngoingNotificationEnabled) { DropdownSetting( title = "Update Interval", selectedValue = settings.ongoingUpdateInterval, values = UpdateInterval.values().toList(), onValueChange = { interval -> viewModel.updateSettings( settings.copy(ongoingUpdateInterval = interval) ) }, label = { it.name.replace("_", " ").lowercase().replaceFirstChar { char -> char.uppercase() } } ) } // Daily Notification Section SectionHeader(title = "Daily Notification") SwitchSetting( title = "Enable Daily Notification", checked = settings.isDailyNotificationEnabled, onCheckedChange = { enabled -> viewModel.updateSettings( settings.copy(isDailyNotificationEnabled = enabled) ) } ) if (settings.isDailyNotificationEnabled) { TimePickerSetting( title = "Notification Time", time = settings.dailyNotificationTime, onTimeChange = { time -> viewModel.updateSettings( settings.copy(dailyNotificationTime = time) ) } ) DropdownSetting( title = "Frequency", selectedValue = settings.dailyNotificationFrequency, values = DailyFrequency.values().toList(), onValueChange = { frequency -> viewModel.updateSettings( settings.copy(dailyNotificationFrequency = frequency) ) }, label = { it.name.replace("_", " ").lowercase().replaceFirstChar { char -> char.uppercase() } } ) } // Severe Alerts Section SectionHeader(title = "Severe Weather Alerts") SwitchSetting( title = "Enable Severe Weather Alerts", checked = settings.isSevereAlertsEnabled, onCheckedChange = { enabled -> viewModel.updateSettings( settings.copy(isSevereAlertsEnabled = enabled) ) } ) // Location Selection SectionHeader(title = "Notification Location") LocationSelectionSetting( selectedLocationId = settings.selectedLocationId, onLocationSelected = { locationId -> viewModel.updateSettings( settings.copy(selectedLocationId = locationId) ) } ) // Test Notification Button( onClick = { if (settings.selectedLocationId != null) { viewModel.testNotification(settings.selectedLocationId) } else { Toast.makeText( context, "Please select a location first", Toast.LENGTH_SHORT ).show() } }, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Text("Test Notification") } } } } } } @Composable fun SectionHeader(title: String) { Text( text = title, style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp) ) } @Composable fun SwitchSetting( title: String, checked: Boolean, onCheckedChange: (Boolean) -> Unit ) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = title, modifier = Modifier.weight(1f) ) Switch( checked = checked, onCheckedChange = onCheckedChange ) } } @Composable fun <T> DropdownSetting( title: String, selectedValue: T, values: List<T>, onValueChange: (T) -> Unit, label: @Composable (T) -> String ) { var expanded by remember { mutableStateOf(false) } Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) { Text( text = title, style = MaterialTheme.typography.bodyMedium ) Box( modifier = Modifier .fillMaxWidth() .clickable { expanded = true } .border(1.dp, MaterialTheme.colorScheme.outline, MaterialTheme.shapes.small) .padding(12.dp) ) { Text(text = label(selectedValue)) DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false } ) { values.forEach { value -> DropdownMenuItem( text = { Text(label(value)) }, onClick = { onValueChange(value) expanded = false } ) } } } } } @Composable fun TimePickerSetting( title: String, time: String, onTimeChange: (String) -> Unit ) { val context = LocalContext.current val timePicker = rememberTimePickerState( initialHour = time.substringBefore(":").toInt(), initialMinute = time.substringAfter(":").toInt() ) var showDialog by remember { mutableStateOf(false) } Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) { Text( text = title, style = MaterialTheme.typography.bodyMedium ) Box( modifier = Modifier .fillMaxWidth() .clickable { showDialog = true } .border(1.dp, MaterialTheme.colorScheme.outline, MaterialTheme.shapes.small) .padding(12.dp) ) { Text(text = time) } } if (showDialog) { TimePickerDialog( onDismissRequest = { showDialog = false }, confirmButton = { TextButton( onClick = { onTimeChange( "${timePicker.hour}:${timePicker.minute}".padStart(5, '0') ) showDialog = false } ) { Text("OK") } }, dismissButton = { TextButton( onClick = { showDialog = false } ) { Text("Cancel") } } ) { TimePicker( state = timePicker, modifier = Modifier.wrapContentSize() ) } } } @Composable fun LocationSelectionSetting( selectedLocationId: Long?, onLocationSelected: (Long) -> Unit ) { // Implement location selection logic here // This would typically fetch locations from your repository and show a dropdown }4. Dependency Injection with Koin
// di/NotificationModule.kt val notificationModule = module { // Data layer single { NotificationSettingsDataStore(get()) } single<NotificationRepository> { NotificationRepositoryImpl(get(), get()) } // Domain layer factory { GetNotificationSettingsUseCase(get()) } factory { UpdateNotificationSettingsUseCase(get()) } factory { GetNotificationContentUseCase(get(), get()) } // Presentation layer viewModel { NotificationViewModel(get(), get(), get(), get(), get()) } }5. Permission Handling
// presentation/components/NotificationPermissionHandler.kt @Composable fun NotificationPermissionHandler( viewModel: NotificationViewModel, content: @Composable () -> Unit ) { val context = LocalContext.current var showPermissionRationale by remember { mutableStateOf(false) } var permissionDenied by remember { mutableStateOf(false) } val launcher = rememberLauncherForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted -> if (!isGranted) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ActivityCompat.shouldShowRequestPermissionRationale( (context as Activity), Manifest.permission.POST_NOTIFICATIONS ) ) { showPermissionRationale = true } else { permissionDenied = true } } } } LaunchedEffect(Unit) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (!viewModel.checkNotificationPermission()) { launcher.launch(Manifest.permission.POST_NOTIFICATIONS) } } } if (showPermissionRationale) { AlertDialog( onDismissRequest = { showPermissionRationale = false }, title = { Text("Notification Permission Required") }, text = { Text("This app needs notification permission to show weather alerts and updates") }, confirmButton = { TextButton( onClick = { showPermissionRationale = false launcher.launch(Manifest.permission.POST_NOTIFICATIONS) } ) { Text("OK") } }, dismissButton = { TextButton( onClick = { showPermissionRationale = false } ) { Text("Cancel") } } ) } else if (permissionDenied) { AlertDialog( onDismissRequest = { permissionDenied = false }, title = { Text("Permission Denied") }, text = { Text("You have permanently denied notification permission. Please enable it in settings.") }, confirmButton = { TextButton( onClick = { permissionDenied = false viewModel.openNotificationSettings() } ) { Text("Open Settings") } }, dismissButton = { TextButton( onClick = { permissionDenied = false } ) { Text("Cancel") } } ) } else { content() } }Implementation Notes
-
Clean Architecture: The implementation follows Clean Architecture with clear separation between domain, data, and presentation layers.
-
Kotlin Coroutines: Used for all asynchronous operations with proper error handling.
-
WorkManager: For scheduling background tasks for notifications.
-
DataStore: For storing notification preferences.
-
Jetpack Compose: For building the UI components.
-
Material3: For consistent theming and components.
-
Arrow: For functional error handling with
Eithertype. -
KotlinX Serialization: Used in the domain models for potential future serialization needs.
-
KISS Principle: Kept the implementation simple and focused on the core functionality.
-
SOLID Principles:
- Single Responsibility: Each class has a single responsibility
- Open/Closed: Designed for extension without modification
- Liskov Substitution: Interfaces can be substituted with implementations
- Interface Segregation: Small, focused interfaces
- Dependency Inversion: Depend on abstractions, not concretions
Next Steps
- Implement the location selection dropdown in the settings screen.
- Add more detailed notification content for expanded view.
- Implement severe weather alert conditions based on your specific requirements.
- Add more comprehensive testing for the notification service.
- Implement proper notification channels and importance levels.
- Add analytics for notification interactions if needed.
This foundation provides a clean, maintainable starting point that you can gradually expand as needed.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.