Files
satiea/app/src/main/java/com/example/notification/MealNotificationManager.kt
T
bleackstorm fe69d7621a feat: implement meal notification system
Add necessary permissions, services, and receivers to support scheduled meal notifications and boot completion handling. Also includes dependency updates and minor test fixes.
2026-11-08 16:57:11 +01:00

175 lines
7.1 KiB
Kotlin

package com.example.notification
import android.app.AlarmManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import com.example.MainActivity
import com.example.R
import com.example.data.model.MealType
import com.example.data.preferences.ReminderPreferencesManager
import com.example.receiver.MealReminderReceiver
import java.util.Calendar
object MealNotificationManager {
private const val TAG = "MealNotificationManager"
const val CHANNEL_ID = "meal_reminders_channel_v2"
const val CHANNEL_NAME = "Rappels de Repas Satiéa"
const val EXTRA_MEAL_TYPE = "extra_meal_type"
const val ACTION_LOG_MEAL = "com.example.action.LOG_MEAL"
fun createNotificationChannel(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(
CHANNEL_ID,
CHANNEL_NAME,
importance
).apply {
description = "Rappels prioritaires pour évaluer votre faim et noter vos repas à table."
enableVibration(true)
vibrationPattern = longArrayOf(0, 250, 200, 250)
setShowBadge(true)
setBypassDnd(false)
}
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
fun showMealNotification(context: Context, mealType: MealType) {
createNotificationChannel(context)
val intent = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
action = ACTION_LOG_MEAL
putExtra(EXTRA_MEAL_TYPE, mealType.name)
}
val pendingIntent = PendingIntent.getActivity(
context,
mealType.ordinal,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0)
)
val (title, body) = when (mealType) {
MealType.BREAKFAST -> Pair("C'est l'heure du petit-déjeuner ☀️", "Prenez un instant pour évaluer votre faim et immortaliser votre assiette.")
MealType.LUNCH -> Pair("Pause déjeuner bien méritée 🥗", "Quel est votre niveau de faim ? Savourez et notez vos sensations.")
MealType.SNACK -> Pair("Moment de la collation 🍎", "Envie gourmande ou vrai besoin d'énergie ? Notez votre ressenti sur Satiéa.")
MealType.DINNER -> Pair("C'est l'heure du dîner 🌙", "Terminez votre journée en douceur en notant votre faim et votre repas.")
}
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification_bell)
.setContentTitle(title)
.setContentText(body)
.setStyle(NotificationCompat.BigTextStyle().bigText(body))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setSound(defaultSoundUri)
.setVibrate(longArrayOf(0, 250, 200, 250))
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.addAction(
R.drawable.ic_notification_bell,
"Noter mon repas",
pendingIntent
)
.build()
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(mealType.ordinal + 100, notification)
}
fun scheduleDailyReminder(context: Context, mealType: MealType, hour: Int, minute: Int, enabled: Boolean) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as? AlarmManager ?: return
val intent = Intent(context, MealReminderReceiver::class.java).apply {
putExtra(EXTRA_MEAL_TYPE, mealType.name)
}
val pendingIntent = PendingIntent.getBroadcast(
context,
mealType.ordinal,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0)
)
if (!enabled) {
alarmManager.cancel(pendingIntent)
Log.d(TAG, "Cancelled reminder for ${mealType.name}")
return
}
val calendar = Calendar.getInstance().apply {
timeInMillis = System.currentTimeMillis()
set(Calendar.HOUR_OF_DAY, hour)
set(Calendar.MINUTE, minute)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
if (timeInMillis <= System.currentTimeMillis()) {
add(Calendar.DAY_OF_YEAR, 1)
}
}
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (alarmManager.canScheduleExactAlarms()) {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
pendingIntent
)
} else {
alarmManager.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
pendingIntent
)
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
pendingIntent
)
} else {
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
pendingIntent
)
}
Log.d(TAG, "Scheduled exact reminder for ${mealType.name} at ${calendar.time}")
} catch (e: SecurityException) {
Log.w(TAG, "Exact alarm permission not granted, falling back to setAndAllowWhileIdle", e)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
pendingIntent
)
}
}
}
fun scheduleAllActiveReminders(context: Context) {
val prefs = ReminderPreferencesManager.getInstance(context)
for (mealType in MealType.entries) {
val enabled = prefs.isReminderEnabled(mealType)
val (hour, minute) = prefs.getReminderTime(mealType)
scheduleDailyReminder(context, mealType, hour, minute, enabled)
}
}
}