vukica
vukica

Reputation: 43

Send notifications to the user through a broadcast reciever when battery level reaches 80% or 25%?

I'm trying for a simple app that alerts the user when the battery reaches certain level. One condition is when it drops to 25% and other when it's at 80 or over while charging so it doesn't get to an overcharging point.

I tried implementing it through a Broadcast receiver in the manifest file. This is my code for the receiver:

package com.example.batterymanager

import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Context.BATTERY_SERVICE
import android.content.Context.NOTIFICATION_SERVICE
import android.content.Intent
import androidx.core.app.NotificationCompat

class BatteryReceiver: BroadcastReceiver() {
    
    

    override fun onReceive(context: Context?, intent: Intent?) {
        fun show80Notification() {
            val notificationManager = context?.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            val notification = NotificationCompat.Builder(context, "channelID")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("Battery at 80!")
                .setContentText("Your phone is at 80%! Stop charging it!")
                .setPriority(NotificationManager.IMPORTANCE_HIGH)
                .setAutoCancel(true)
                .build()
            notificationManager.notify(1, notification)

        }

        fun showLowNotification() {
            val notificationManager = context?.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            val notification = NotificationCompat.Builder(context, "channelID")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("Battery low!")
                .setContentText("Your phone is at 25%! Charge it now!")
                .setPriority(NotificationManager.IMPORTANCE_HIGH)
                .setAutoCancel(true)
                .build()
            notificationManager.notify(1, notification)

        }

        when (context?.getSystemService(BATTERY_SERVICE)) {
            80 -> {
                show80Notification()
            }

            25 -> {
                showLowNotification()
            }
        }

    }


}

What am I doing wrong? Nothing happens when battery reaches that level.

Upvotes: 0

Views: 32

Answers (0)

Related Questions