is Battery Charging - Android Hardware

Android examples for Hardware:Battery

Description

is Battery Charging

Demo Code


//package com.java2s;
import android.app.Application;

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

public class Main {
    public static boolean isCharging() {
        try {/*from  w w  w.  ja va 2s .  c om*/
            IntentFilter ifilter = new IntentFilter(
                    Intent.ACTION_BATTERY_CHANGED);
            Intent batteryStatus = getApplicationUsingReflection()
                    .registerReceiver(null, ifilter);
            int status = batteryStatus.getIntExtra(
                    BatteryManager.EXTRA_STATUS, -1);
            boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
                    || status == BatteryManager.BATTERY_STATUS_FULL;
            if (isCharging) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public static Application getApplicationUsingReflection()
            throws Exception {
        return (Application) Class.forName("android.app.ActivityThread")
                .getMethod("currentApplication")
                .invoke(null, (Object[]) null);
    }
}

Related Tutorials