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?

  • Is it possible to use content:// as a source for an <audio> element in a WebView
  • Do you know a good android rendering engine?
  • How to make a custom private plugin in phonegap
  • how to install unsigned android application on the device?
  • How to play video using FFMPEG library in Android?
  • OnItemCLickListener not working in listview
  • Related posts:

    How can I make a TextView automatically scroll as I add more lines of text?
    Accessing video stream from Looxcie device
    defined xml layout in layout-land does not appear in android application
    How to set a Fragment tag by code?
    How can I add an Action Bar Item during run time
    Can I have &ldquo;adjustResize&rdquo; soft keyboard behavior and a toolbar behind the status...
  • IOException thrown by AccountManagerFuture.getResults whereas connection is alive
  • What goes into Source Control?
  • Capture screen shot of GoogleMap Android API V2
  • Android Toolbar and User Image Animation Like Twitter
  • Retrofit map json variable to keyword
  • Adding an image as textview's text background
  • 8 Solutions collect form web for “Check if device is plugged in”

    Thanks to CommonsWare here is the code I wrote.

    public class PowerUtil {
        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;
        }
    }
    
    public static boolean isPlugged(Context context) {
        boolean isPlugged= false;
        Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        isPlugged = plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
        if (VERSION.SDK_INT > VERSION_CODES.JELLY_BEAN) {
            isPlugged = isPlugged || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS;
        }
        return isPlugged;
    }
    

    A minor update to support Wireless charging.

    Call registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)). This will return an Intent that has extras defined on BatteryManager to let you know if it is plugged in or not.

    This works because Intent.ACTION_BATTERY_CHANGED is a sticky broadcast.

    Your answer is in the android reference !

    Here is the example code:

    // Are we charging / charged?
    int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                     status == BatteryManager.BATTERY_STATUS_FULL;
    
    // How are we charging?
    int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
    boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
    

    Easy way is to use an intent filter ACTION_BATTERY_CHANGED

    public void checkBatteryState(View sender) {
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = registerReceiver(null, filter);
    
        int chargeState = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        String strState;
    
        switch (chargeState) {
            case BatteryManager.BATTERY_STATUS_CHARGING:
            case BatteryManager.BATTERY_STATUS_FULL:
                strState = "charging";
                break;
            default:
                strState = "not charging";
        }
    
        TextView tv = (TextView) findViewById(R.id.textView);
        tv.setText(strState);
    }
    

    try this:

    public class PowerConnectionReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
    
            IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            Intent batteryStatus = context.registerReceiver(null, ifilter);
    
    
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            boolean isCharging =    status == BatteryManager.BATTERY_STATUS_CHARGING ||
                                    status == BatteryManager.BATTERY_STATUS_FULL;
    
            int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
            boolean usbCharge   = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
            boolean acCharge    = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
    
    
            if (batteryStatus != null) {
                int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                float batteryPct = level / (float) scale;
            }
    
    
        }//end onReceive
    
    
    }//end PowerConnectionReceiver
    
    BroadcastReceiver receiver = new BroadcastReceiver() {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if(action.equalsIgnoreCase(ACTION_POWER_CONNECTED))
            {
    
    
                    if(chargerConnected != null )
                    {
                        chargerConnected.setText("Cable Connected");
                    }
                    if(chargerImage != null )
                    {
                        chargerImage.setImageDrawable(getResources().getDrawable(R.drawable.usb));
                    }
    
            }else if(action.equalsIgnoreCase(ACTION_POWER_DISCONNECTED))
            {
    
    
                    if(chargerConnected != null )
                    {
                        chargerConnected.setText("NOT CHARGE");
                    }
                    if(chargerImage != null )
                    {
                        chargerImage.setImageDrawable(getResources().getDrawable(R.drawable.battery_icon));
                    }
    
                try {
    
                    Toast.makeText(context, "Power Cable Disconnected", Toast.LENGTH_SHORT).show();
                }catch (Exception e){e.printStackTrace();}
    
            }
        }
    };
    

    It’s a sticky intent, you don’t need to register a BroadcastReceiver—by simply calling registerReceiver passing in null as the receiver as shown in the next snippet, the current battery status intent is returned. You could pass in an actual BroadcastReceiver object here, but we’ll be handling updates in a later section so it’s not necessary.

    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = context.registerReceiver(null, ifilter);
    

    You can extract both the current charging status and, if the device is being charged, whether it’s charging via USB or AC charger:

    // Are we charging / charged?
    int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                         status == BatteryManager.BATTERY_STATUS_FULL;
    
    // How are we charging?
    int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
    boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
    

    The BatteryManager broadcasts an action whenever the device is connected or disconnected from power. It’s important to receive these events even while your app isn’t running—particularly as these events should impact how often you start your app in order to initiate a background update—so you should register a BroadcastReceiver in your manifest to listen for both events by defining the ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED within an intent filter.

    <receiver android:name=".PowerConnectionReceiver">
      <intent-filter>
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
        <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
      </intent-filter>
    </receiver>
    

    Within the associated BroadcastReceiver implementation, you can extract the current charging state and method as described in the previous step.

    public class PowerConnectionReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                                status == BatteryManager.BATTERY_STATUS_FULL;
    
            int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
            boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
            boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
        }
    }
    
    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.