30

Is there an easy way to be notified when USB or AC power is connected to an Android phone?

6 Answers 6

76

In AndroidManifest.xml

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <receiver android:name=".receiver.PlugInControlReceiver">
        <intent-filter>
            <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
            <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
        </intent-filter>
    </receiver>
</application>

In Code

public class PlugInControlReceiver extends BroadcastReceiver {
   public void onReceive(Context context , Intent intent) {
       String action = intent.getAction();

       if(action.equals(Intent.ACTION_POWER_CONNECTED)) {
           // Do something when power connected
       }
       else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
           // Do something when power disconnected
       }
   }
}
6
  • 4
    Note that the onReceive() method should be in the PlugInControlReceiver class which extends BroadcastReceiver. Apr 3, 2014 at 8:58
  • 2
    Thanks for kind explaination @OdedBreiner
    – J.J. Kim
    Apr 7, 2014 at 6:35
  • but above solution doesn't work for VIVO and OPPO mobile phones
    – Ashish
    May 29, 2017 at 5:51
  • 5
    You cannot register receivers in the manifest for most implicit broadcasts on Android 8 and newer due to background execution limitations.
    – mike47
    Apr 27, 2019 at 20:01
  • 1
    How to do it on Android 8 or newer?
    – Benur21
    Jul 22, 2021 at 22:59
10

Set up a BroadcastReceiver for ACTION_BATTERY_CHANGED. An Intent extra will tell you what the charging state is -- see BatteryManager for details.

3
  • @NPike: see the comments on this accepted answer for another question — one can get the current state using the method shown there without subscribing.
    – Paul Ruane
    Mar 9, 2011 at 14:03
  • 1
    Tu be precise: Intent ix = main.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); boolean plugged = ix != null && ix.getIntExtra("plugged", 0) != 0;
    – mdiener
    Sep 16, 2013 at 14:23
  • 17
    DO NOT USE ACTION_BATTERY_CHANGED because at 99% battery full, Android will broadcast an event that shows the power is disconnected and the battery is discharging (even though the phone is still connected to AC power!). Instead, use ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED Oct 17, 2016 at 10:07
8

another way is using battery manager. this i usable for api>=21

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;
    }
}
5

Here is another way to poll the information:

read the values here:ex.

via android shell:

cat /sys/class/power_supply/usb/online

1=connected, 0=not. Reflects USB connection status.

cat /sys/class/power_supply/ac/online

1=connected, 0=not. Reflects AC connection status.

Using both of these together, I think will tell whether the device is receiving power or not. Not sure if the location is the same for all devices. Found the location the same though on android 7+ and 5+, on a Samsung tablet and a RockChip device.

For the devices I mentioned tested, it worked. Files are RO, read only, you would only read them to poll the information. The android API's did not provide the level of detail I needed at the version I was required to use (5.1.1), this did. I used provided android API to create a process run those commands. It doesn't require root. This was done for an kiosk app. You can also run the same process using only android API (file, FileReader, etc).

Here is an Android API example:

File aFile = new File("/sys/class/power_supply/ac/online");
try {
    BufferedReader br = new BufferedReader(new FileReader(aFile));
    char aBuff[] = new char[1];
    int aCount = br.read(aBuff,0, 1);
    Log.d(TAG, "run: Res:"+new String(aBuff));
}catch(Exception e){
    Log.d(TAG, "Exception:Error:run: "+e.toString());
}
3
  • This will not work - that file is RO, I get 'permission' denied. Please use Android APIs and not Linux low level APIs :)
    – elcuco
    Mar 13, 2018 at 14:30
  • 1
    Why downvote? It's working and can be used for some bash scripting and ROM customizations. I really appreciate this answer. But it should not be used from java of course.
    – POMATu
    Feb 18, 2019 at 18:24
  • 1
    Update: This answer works even without root. It can be used as fallback method for getting the value. On some custom ROMs normal broadcasts for charging event is broken somehow
    – POMATu
    Feb 28, 2019 at 20:52
1

from Android doc, just do like this

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

        // 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;
-2

One thing more you must check whether there is errors in Manifest--->application. If then click on the field showing error and just click on the link "Name" Then dialogue box appears for adding a class. add the class and in the class copy the code of on receive.That is the code above should be copied in the class file not the main activity. Thanks Pzycoderz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.