How to Check if the Battery is Charging or Not in Android Programmatically? - GeeksforGeeks

23 Feb, 2021
The charging status can change as quickly as a device can be plugged in, so it’s crucial to monitor the charging state for changes and alter your refresh rate accordingly. The BatteryManager broadcasts an action whenever the device is connected or disconnected from power. It is important to receive these events even while the app isn’t running significantly. Such events should impact how often you start the app to initiate a background update. So you should register a BroadcastReceiver in the manifest to listen for both events by defining the ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED within an intent filter (filter). A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. Keep an eye on the battery status in the status bar.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file, which represents the UI of the project. Add a Button, so whenever the user will click on the Button a Toast message with battery state (charging or not) will be popped up on the screen. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout     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">      <Button        android:id="@+id/btn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:text="Click"        />  </RelativeLayout>
Step 3: Working with the MainActivity.kt file
Finally, go to the MainActivity.kt file, and refer the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.content.Intentimport android.content.IntentFilterimport android.os.BatteryManagerimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toast  class MainActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // Button onclick will display the status of charging        val btn = findViewById<Button>(R.id.btn)                  btn.setOnClickListener {                // Intent to check the actions on battery            val batteryStatus: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter ->                applicationContext.registerReceiver(null, ifilter)            }              // isCharging if true indicates charging is ongoing and vice-versa            val status: Int = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1            val isCharging: Boolean = status == BatteryManager.BATTERY_STATUS_CHARGING                    || status == BatteryManager.BATTERY_STATUS_FULL                // Display whatever the state in the form of a Toast            if(isCharging) {                Toast.makeText(applicationContext, "Charging", Toast.LENGTH_LONG).show()            } else {                Toast.makeText(applicationContext,"Not Charging", Toast.LENGTH_LONG).show()            }        }    }}
Keep an eye on the battery status in the status bar.
Android-Misc
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters