is Phone Plugged In - Android android.os

Android examples for android.os:BatteryManager

Description

is Phone Plugged In

Demo Code

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;

public class Main {

  public static boolean isPhonePluggedIn(Context context) {
    boolean charging = false;

    final Intent batteryIntent = context.registerReceiver(null,
        new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean batteryCharge = status == BatteryManager.BATTERY_STATUS_CHARGING;

    int chargePlug = batteryIntent
        .getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
    boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

    if (batteryCharge)
      charging = true;/*from   w  w  w  . j av  a2  s  .c o  m*/
    if (usbCharge)
      charging = true;
    if (acCharge)
      charging = true;

    return charging;
  }

}

Related Tutorials