Well, let me start by looking a lot for the answer to this question. I am trying to figure out what is the best practice and what works best for battery life. Here is my situation:
I want my application to pause when the device reaches a certain battery level and should not use Intent.ACTION_BATTERY_LOW and Intent.ACTION_BATTERY_OKAY. I have seen this option in many programs and would like to imitate it with my application.
I understand that Intent.ACTION_BATTERY_CHANGED must be a registered event. You cannot just declare it in the manifest for BroadcastReceiver to receive this receiver in order to receive the intent. I know how to encode, how to get the battery level / scale and see if the device is charging via USB or AC
My current thinking process has led me to two options, and I canโt find out which one is better, or if there is another option that I donโt know about? Maybe someone can help me with the pros and cons of options to help me?
Option 1: Create a repeating alarm using the AlarmManager to basically poll the device each time to check the battery level. So when my alarm goes off, it will send an individual intent for my registered receiver to check the battery level.
PRO does not work background service, which can be killed or eat battery life.
CONs do not detect a real-time connection / disconnection of the device from the charging source and are forced to rely on the next alarm to detect a change.
Option 2: Create a service that registers the receiver for Intent.ACTION_BATTERY_CHANGED so that it not only receives the battery level when it is broadcast by the system, but also detects changes in charging in real time.
PRO realtime detection of changes in battery life and change in charging method.
CON is a permanent job service that can be killed
CON eats up processing time and battery life to save detection
Battery Level:
Get the battery level before the broadcast receiver answers Intent.ACTION_BATTERY_CHANGED
Intent batteryIntent = context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int rawlevel = batteryIntent.getIntExtra("level", -1); double scale = batteryIntent.getIntExtra("scale", -1); double level = -1; if (rawlevel >= 0 && scale > 0) { level = rawlevel / scale;
Turn on / charge:
USB connection charging signals for Android
public static boolean isConnected(Context context) { Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB; }
}
Thanks in advance -H