To check the battery percentage in Android using Kotlin, you can use the BatteryManager
system service. Here’s a simple example:
- Add the necessary permission to your AndroidManifest.xml:
<uses-permission android:name="android.permission.BATTERY_STATS" />
MainActivity.kt
package com.androindian.broad
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.BatteryManager.BATTERY_PROPERTY_CAPACITY
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.androindian.broad.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
var binding: ActivityMainBinding?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= DataBindingUtil.setContentView(this,R.layout.activity_main)
this.registerReceiver(this.mBatInfoReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
val mBatInfoReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(ctxt: Context, intent: Intent) {
val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
val batteryPct = level * 100 / scale.toFloat()
binding?.show?.text = "$batteryPct%"
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/show"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/percentage"
android:text="check battary"/>
</LinearLayout>
</layout>