Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if device is plugged in

My app has a broadcast receiver to listen for changes to ACTION_POWER_CONNECTED, and in turn flag the screen to stay on.

What I am missing is the ability for the app to check the charging status when it first runs. Can anyone please help me with code to manually check charging status?

like image 419
Josh Avatar asked Mar 12 '11 15:03

Josh


People also ask

What happens if you leave a device plugged in even after it is charged?

If you leave a device plugged in even after it is charged 100% It can over-heat.


1 Answers

Thanks to CommonsWare here is the code I wrote.

public class Power {     public static boolean isConnected(Context context) {         Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));         int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);         return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS;     } }  if (Power.isConnected(context)) {     ... } 

or the Kotlin version

object Power {     fun isConnected(context: Context): Boolean {         val intent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))         val plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)         return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS     } } 

http://developer.android.com/training/monitoring-device-state/battery-monitoring.html

like image 133
Geekygecko Avatar answered Oct 14 '22 05:10

Geekygecko