我想检测充电器或USB之类的东西是否连接到设备的充电器端口。有没有办法实现这一点?
我试过这个链接。它在充电器连接和断开时有效。它适用于所有设备吗?
提前致谢
是的,您可以通过意图广播监控电池状态。
电池监视器示例:
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;
}
}
}