0

I need to make an application that determine the level of battery , if it's under 15% i'll make something.

This is my BroadCast:

public class BatteryChecker extends BroadcastReceiver {



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


    int level = intent.getIntExtra("level", 0);


        Toast.makeText(context,"Battery : "+level+"%",Toast.LENGTH_LONG).show();


      }
}

but when i register the receiver in manifest it doesn't work

<receiver android:name=".BatteryChecker">

        <intent-filter>
            <action android:name="android.intent.action.BATTERY_CHANGED"></action>
        </intent-filter>

    </receiver>

when i register it programmatically it works , but i need to register it through manifest

iosamammohamed
  • 317
  • 3
  • 18

1 Answers1

1

but i need to register it through manifest

That is not possible. Android limits certain broadcasts, such as ACTION_BATTERY_CHANGED, to receivers that are registered via registerReceiver().

You can register for ACTION_BATTERY_LOW in the manifest, which would be a much more efficient way to find out when the battery is low.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • okay, is there any way to get the battery level in ACTION_BATTERY_LOW ? – iosamammohamed Mar 21 '17 at 15:37
  • @iosamammohamed: On API Level 21+ (Android 5.0+), use `BatteryManager`. On older versions, call `registerReceiver()` for `ACTION_BATTERY_CHANGED` with a `null` `BroadcastReceiver` -- the return value should be the last sticky `ACTION_BATTERY_CHANGED` broadcast, and you can pick the extras off of there. – CommonsWare Mar 21 '17 at 15:51