I am an android developer working in Xamarin. I am relatively new to iOS.
I want to detect, from my app, when the battery becomes low.
In android I implemented using BroadcastReceiver
.
Although in iOS I am unable to find a pub-sub model like that of android.
In iOS I want register a broadcast receiver for low battery broadcasts from the OS, so that I be notified in the app should the battery become low.
Even swift code is acceptable. I can make it work in Xamarin from there.
Below is my Xamarin code for android implementation.
public class AppBatteryBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
int level = intent.GetIntExtra(BatteryManager.ExtraLevel, -1);
int scale = intent.GetIntExtra(BatteryManager.ExtraScale, -1);
int levelPercentage = (level != -1 && scale != -1) ? (int)Math.Floor(level * 100D / scale) : 101;
}
}
I am registering an instance of this class from my MainActivity.cs like below
var intentFilter = new IntentFilter();
intentFilter.AddAction(Intent.ActionBatteryChanged);
RegisterReceiver(_batteryBroadcastReceiver, intentFilter);
In android every time battery changes I get notified in the OnReceive
method above. From there I can check if the battery is below a certain level.