How to detect power connected state?

前端 未结 5 1413
庸人自扰
庸人自扰 2020-11-30 13:24

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

5条回答
  •  眼角桃花
    2020-11-30 14:13

    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());
    }
    

提交回复
热议问题