Check if the Device is Charging in Android and the Power Source.

By | February 3, 2017

Your application peformance should be upto the mark. But it should perform differently not on the front end , but on the back end when it the device is connected to a power source or charging. Charging could be of from USB and from wire cable. When your device is charging itself , it is recommended to update your application settings if any, such as maximizing your refresh rate whenver the device is connected. It can be done as this.


	IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); 
	// Are we charging / charged? Full or charging. 
	Intent batteryStatus = context.registerReceiver(null, ifilter); 
	// How are we charging? From AC or USB. 
	int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); 
	int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);

Lets see how the complete code look like….

MainActivity


import android.os.BatteryManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;

public class MainActivity extends Activity {
    private BatteryManager battery;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = registerReceiver(null, ifilter);
        int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
		// Find the charge Source
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING 
                               || status == BatteryManager.BATTERY_STATUS_FULL; 
        int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
        if (usbCharge) {
            Toast.makeText(getApplicationContext(), 
                   "Mobile is charging on USB", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), 
                   "Mobile is charging on AC", Toast.LENGTH_LONG).show();
        }

    }

}

Done.

Send your comments to coderzheaven@gmail.com.

Leave a Reply

Your email address will not be published. Required fields are marked *