This question already has an answer here:
-
Check if device is plugged in
9 answers
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
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;
}
}
}