30

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

NPike
  • 13,136
  • 12
  • 63
  • 80

6 Answers6

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
       }
   }
}
MBH
  • 16,271
  • 19
  • 99
  • 149
J.J. Kim
  • 1,845
  • 1
  • 16
  • 21
10

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

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • @NPike: see the comments on this [accepted answer](http://stackoverflow.com/questions/3997289/get-temperature-of-battery-on-android/3997349#3997349) for another question — one can get the current state using the method shown there without subscribing. – Paul Ruane Mar 09 '11 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 '13 at 14:23
  • 16
    ***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 – Someone Somewhere Oct 17 '16 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;
    }
}
iman kazemayni
  • 1,255
  • 1
  • 19
  • 20
4

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());
}
  • 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 '18 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 '19 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 '19 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;
kevin liu
  • 23
  • 3
-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

Girish Sasidharan
  • 582
  • 1
  • 5
  • 14