Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Thanks to CommonsWare here is the code I wrote.</p> <pre><code>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)) { ... } </code></pre> <p>or the Kotlin version</p> <pre><code>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 } } </code></pre> <p>Note BatteryManager.BATTERY_PLUGGED_WIRELESS requires API Level 17 (Jelly Bean MR1). For backward compatibility change the last line to:</p> <pre><code>return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.JELLY_BEAN_MR1 &amp;&amp; plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS) </code></pre> <p><a href="http://developer.android.com/training/monitoring-device-state/battery-monitoring.html" rel="noreferrer">http://developer.android.com/training/monitoring-device-state/battery-monitoring.html</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload