I created a Kotlin app who should give an alarm when a defined number of thinks is reached. In the emulator it is working fine and also when the app is open. But when the app is closed, the alarm is not triggered on my Huawei and Samsung phone. I tried the following:
- Change settings on Phones (app notifications, battery management)
- Try it on different phones (Huawei and Samsung)
- I added the words "alarm" to the package name
- Built and tried release version
Unfortunately nothing helps.
private fun setAlarm(timeInMillis: Long) {
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, MyAlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0)
alarmManager.set(
AlarmManager.RTC,
timeInMillis,
pendingIntent
)
//Alarm deaktiviert
if ((actual_alarm_on_off =="OFF" && actual_alarm_on_off != "ON1") || (alarmReleased == true && actual_alarm_on_off != "ON1")){
alarmManager.cancel(pendingIntent)
}
}
class MyAlarmReceiver: BroadcastReceiver(){
companion object {
const val NOTIFICATION_ID = 100
const val NOTIFICATION_CHANNEL_ID = "1000"
}
override fun onReceive(context: Context, intent: Intent) {
createNotificationChannel(context)
notifyNotification(context)
}
private fun createNotificationChannel(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
"@string/app",
NotificationManager.IMPORTANCE_HIGH
)
NotificationManagerCompat.from(context).createNotificationChannel(notificationChannel)
}
}
private fun notifyNotification(context: Context) {
with(NotificationManagerCompat.from(context)) {
val build = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setContentTitle("Pillen-Zähler Alarm")
.setContentText("Medikament bald aufgebraucht!")
.setSmallIcon(R.drawable.ic_baseline_warning_24)
.setPriority(NotificationCompat.PRIORITY_HIGH)
notify(NOTIFICATION_ID, build.build())
}
}
}
<receiver android:name="com.example.medbesteller_alarm.MyAlarmReceiver"
android:exported="false"/>