How to identify the connection to charger port? [duplicate]

旧时模样 提交于 2019-12-08 05:59:44

问题


I want to detect is anything like charger or USB is connected to the charger port of a device.Is there anyway to achieve this?

I tried this link .It works when charger connected and disconnected.Is it works in all devices?

Thanks in Advance


回答1:


Yes, you can monitor battery status via intent broadcasts.

Example of a battery monitor:

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

public class ChargeMon extends BroadcastReceiver {
    private boolean mCharging;
    private boolean mUsb;
    private boolean mAC;

    public void start(Context c) {
        c.registerReceiver(this, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    public void stop(Context c) {
        c.unregisterReceiver(this);
    }

    public boolean isCharging() {
        return mCharging;
    }

    public boolean isUsb() {
        return mUsb;
    }

    public boolean isAC() {
        return mAC;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if(Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())){
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);

            mCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                       status == BatteryManager.BATTERY_STATUS_FULL;

            int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);

            mUsb = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
            mAC = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
        }
    }
}


来源:https://stackoverflow.com/questions/17440729/how-to-identify-the-connection-to-charger-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!