How to Check the Type of Charging (USB/AC) in Android Programmatically?
Last Updated :
14 Aug, 2024
When altering the frequency of the background updates to scale back the effect of these updates on battery life, checking the present battery level and charging state is a superb place to start. The battery-life impact of performing application updates depends on the battery level and charging state of the device. The effect of performing updates while the device is charging over AC is negligible, so in most cases, maximize the refresh rate whenever the device is connected to a wall charger. Conversely, if the device is discharging, reducing the update rate helps prolong the battery life. Similarly, you'll check the battery charge level, potentially reducing the frequency of—or even stopping—the updates when the battery charge is almost exhausted. There are 2 types of charging in any smartphone:
- USB Charging: Universal Serial Bus Charging: Charging from USB outlets such as USB port of a Laptop: 500 milliamps max.
- AC Charging: Alternating Current Charging: Charging from a wall charger: 2 amps max.
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.
Approach
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 types of battery charging 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.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Button onclick will display the type 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
// usbCharge is true when connected to usb port and same with the ac wall charger
val chargePlug: Int = batteryStatus?.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) ?: -1
val usbCharge: Boolean = chargePlug == BatteryManager.BATTERY_PLUGGED_USB
val acCharge: Boolean = chargePlug == BatteryManager.BATTERY_PLUGGED_AC
// Display whatever the state in the form of a Toast
when {
usbCharge -> {
Toast.makeText(applicationContext, "USB Charging", Toast.LENGTH_LONG).show()
}
acCharge -> {
Toast.makeText(applicationContext, "AC Charging", Toast.LENGTH_LONG).show()
}
else -> {
Toast.makeText(applicationContext, "Not Charging", Toast.LENGTH_LONG).show()
}
}
}
}
}
Output: Run on Physical Device
Keep an eye on the battery status in the status bar. The sequence of actions:
- Initially not connected.
- Connected to the USB port of the laptop.
- Disconnected.
- Connected to AC wall charger.
- Disconnected.
Similar Reads
How to Check if the Battery is Charging or Not in Android Programmatically? 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 Battery Manager broadcasts an action whenever the device is connected or disconnected from power. It is important to receive
3 min read
How to Check the Battery Level in Android Programmatically? Sometimes, it is useful to determine the current battery level. One may choose to reduce the rate of your background updates if the battery charge is below a certain level. But one cannot continuously monitor the battery state. In general, the impact of constantly monitoring the battery level has a
2 min read
How to Get the MAC of an Android Device Programmatically? MAC stands for Media Access Control. The MAC address is also known as the Equipment Id Number. This MAC Address is provided by the Network Interface Card. In this article, we will see step by step from creating a new empty project to How to make an android app to display MAC Address using Java. Note
2 min read
How to Check Airplane Mode State in Android Programmatically? Airplane Mode is often seen in action during flights, avoiding calls, or rebooting the network on mobiles, tablets, and laptops. Airplane mode is a standalone mode where the device turns down the radio communications. These may include Wifi, GPS, Telephone Network, Hotspot depending upon the year of
3 min read
How to Check if the Battery is Charging or not in Android Programmatically using Jetpack Compose? Many times while building an android application we have to check the charging status of the battery whether the battery is currently charging or not. For checking the battery charging status within the android application. We use battery manager. In this article, we will take a look at How to use B
5 min read