0

I want to perform some task when I get ACTION_BOOT_COMPLETED intent, i'm using following code to check if device is plugged in but I get method is undefined for the type BootReceiver at registerReceiver. Can anyone find the solution? here is what i'm doing.

public class BootReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, Intent intent) {

    if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {

    if(isCharging())
    doSomething();  //something to perform after boot if plugged in

        }



        public boolean isCharging() {
    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = registerReceiver(null, filter); //getting error here

    boolean strState;

    int chargeState = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

    switch (chargeState) {
        case BatteryManager.BATTERY_STATUS_CHARGING:
        case BatteryManager.BATTERY_STATUS_FULL:
            strState = true;
            break;
        default:
            strState = false;
    }
    return strState;

    }

}
Aahil
  • 33
  • 2
  • 7

1 Answers1

3

Call registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)). This will return an Intent that has extras defined on BatteryManager to let you know if it is plugged in or not.

This works because Intent.ACTION_BATTERY_CHANGED is a sticky broadcast.

Answer picked from Check if device is plugged in by CommonsWare

UPDATE: Please call context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); this method is defined in context

Community
  • 1
  • 1
Mustansar Saeed
  • 2,730
  • 2
  • 22
  • 46