如果 Kotlin 在 Android 中电池电量低于 10%,则显示通知

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

如果 Kotlin 使用广播接收器在 Android 工作室中电池电量低于 10%,我该如何显示通知?

在清单中添加权限。注册您的广播接收器。在本教程中阅读更多内容 https://developer.android.com/training/monitoring-device-state/battery-monitoring

中用这个创建一个新的 Android 项目

将 AndroidX 支持库添加到您的 模块的 build.gradle(其他 implementation 是:

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

MainActivity.kt 进口:

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
            }
        }
    }
}