Search code examples
androidkotlinnotificationsbattery

Display notification if the battery becomes less than 10% in Android by Kotlin


How can I display a notification if the battery becomes less than 10% in an Android studio by Kotlin using a broadcast receiver?


Solution

  • Create a new Android project with this in the

    Add the AndroidX support library to your module's build.gradle (where the other implementations are:

    dependencies {
        implementation 'androidx.core:core-ktx:1.3.2'
    }
    

    MainActivity.kt Imports:

    import android.app.NotificationChannel
    import android.app.NotificationManager
    import android.content.Context
    import android.content.Intent
    import android.content.IntentFilter
    import android.os.BatteryManager
    import android.os.Build
    import android.os.Bundle
    import androidx.annotation.RequiresApi
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.app.NotificationCompat
    import kotlin.concurrent.thread
    

    MainActivity.kt:

    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            thread {
                val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    
                val mChannel = NotificationChannel("default", "default", NotificationManager.IMPORTANCE_DEFAULT)
                mNotificationManager.createNotificationChannel(mChannel)
    
                while (true) {
                    val batteryStatus: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter ->
                        this.registerReceiver(null, ifilter)
                    }
                    val batteryPct: Float = batteryStatus?.let { intent ->
                        val level: Int = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                        val scale: Int = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
                        level * 100 / scale.toFloat()
                    } ?: 100f
    
                    if (batteryPct <= 10) {
                        val notif = NotificationCompat.Builder(this, "default").setContentText("Low Battery: ${batteryPct.toInt()}%").setSmallIcon(R.drawable.ic_launcher_foreground).build()
                        mNotificationManager.notify(1, notif)  // re-use notification in tray
                    }
    
                    Thread.sleep(20000)  // check every 20 seconds
                }
            }
        }
    }