Returns true if the device is plugged in to AC, or USB. - Android Hardware

Android examples for Hardware:Device Feature

Description

Returns true if the device is plugged in to AC, or USB.

Demo Code


//package com.java2s;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import android.os.BatteryManager;

public class Main {
    /**/* w w w. j a  v a 2  s  .c o  m*/
     * Returns true if the device is plugged in to AC, or USB. On devices with API 17 or higher,
     * this will return true if the device is being charging wirelessly as well.
     * 
     * @param context
     * @return
     */
    public static boolean isPluggedIn(Context context) {
        Intent intent = context.registerReceiver(null, new IntentFilter(
                Intent.ACTION_BATTERY_CHANGED));
        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        // 4 = Wireless charging added in API 17
        return plugged == BatteryManager.BATTERY_PLUGGED_AC
                || plugged == BatteryManager.BATTERY_PLUGGED_USB
                || plugged == 4;
    }
}

Related Tutorials