Search code examples
androidbatterylevelbatterymanager

Battery status in android


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


Solution

  • 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.