如何识别与充电器端口的连接?

时间:2013-07-03 05:59:52

标签: android connection port detect

我想检测是否有类似充电器或USB连接到设备的充电器端口。无论如何要实现此目的吗?

我试过这个link。当充电器连接和断开连接时它可以正常工作。它适用于所有设备吗?

先谢谢

1 个答案:

答案 0 :(得分:1)

是的,您可以通过意向广播来监控电池状态。

电池监视器示例:

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