Check If Battery Optimization Is Enabled or Not for an App

Check if battery optimization is enabled or not for an app

This one was a bit tricky to track down: here's what you are looking for

PowerManager.isIgnoringBatteryOptimizations()

Xamarin Forms - How to check setting of RequestIgnoreBatteryOptimizations permission on Android

From this document, there are two ways to set Battery Optimization

An app can fire the ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS intent to take the user directly to the Battery Optimization, where they can add the app.

An app holding the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission can trigger a system dialog to let the user add the app to the exemption list directly, without going to settings. The app fires a ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS Intent to trigger the dialog.

I use PowserManager.isIgnoringBatteryOptimizations to check Battery Optimization.

Firstly, add RequestIgnoreBatteryOptimizations in AndroidManifest.xml

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

Then creating Interface in Shared code.

public interface IBattery
{
void getbattery();
}

Implementing this interface in Android platform.

[assembly: Dependency(typeof(ImplementBattery))]
namespace FormsSample.Droid
{
public class ImplementBattery : IBattery
{
public void getbattery()
{
Intent intent = new Intent();
String packageName = MainActivity.mac.PackageName;
PowerManager pm = (PowerManager)MainActivity.mac.GetSystemService(Context.PowerService);
if (pm.IsIgnoringBatteryOptimizations(packageName))
intent.SetAction(Android.Provider.Settings.ActionIgnoreBatteryOptimizationSettings);
else
{
intent.SetAction(Android.Provider.Settings.ActionRequestIgnoreBatteryOptimizations);
intent.SetData(Android.Net.Uri.Parse("package:" + packageName));
}
MainActivity.mac.StartActivity(intent);
}
}
}

Creating static Mainactivity field in Mainactivity.cs.

  public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
public static MainActivity mac;
protected override void OnCreate(Bundle savedInstanceState)
{
initFontScale();
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;

base.OnCreate(savedInstanceState);

mac = this;

Now, using DependencyService to fire.

   private void Button_Clicked(object sender, EventArgs e)
{
DependencyService.Get<IBattery>().getbattery();
}

Sample Image

Android: Check if my app is allowed to run background activities

I see that it does not work for me also. So, you can see my two classes in my Git repo which I had also provided you within my previous answer. Also my repo link is here. Here you must see this in my AndroidManifest.xml and this method and this overridden method.

There I am asking for the ignore battery optimization permission and if it is enabled, it works fine or it if not enabled, asks for that permission.

Also, you can view the result in relation to this question's answer. This is the result


If that does not work, refer to this code:

String packageName = getPackageName();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
Toast.makeText(this, "no allowed", Toast.LENGTH_SHORT).show();
// it is not enabled. Ask the user to do so from the settings.
}else {
Toast.makeText(this, "allowed", Toast.LENGTH_SHORT).show();
// good news! It works fine even in the background.
}

And to take the user to this setting's page, based on this answer:

Intent notificationIntent = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
String expandedNotificationText = String.format("Background activity is restricted on this device.\nPlease allow it so we can post an active notification during work sessions.\n\nTo do so, click on the notification to go to\nApp management -> search for %s -> Battery Usage -> enable 'Allow background activity')", getString(R.string.app_name));
notificationBuilder.setContentIntent(pendingIntent)
.setContentText("Background activity is restricted on this device.")
.setStyle(new NotificationCompat.BigTextStyle().bigText(expandedNotificationText))

How to exclude an Android App from Battery Optimization using code

I think you're having 2 different problems:

1) If you want to keep your app in background you should use a foreground Service. That way your app won't be considered to be in background by the system and the chances of its process being killed are reduced drastically. The downside is that as long as your Service is in foreground you need to show a permanent notification.

2) You cannot exclude your app from battery optimization yourself, but you can prompt the user the settings to whitelist your app. In order to do that you can refer to the official docs, you'll need to add the Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission to the manifest and then launch an intent with action ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS. The user will then be able to whitelist your app, only she/he can do that because otherwise every app would whitelist itself and the purpose of the battery optimization would be defied.



Related Topics



Leave a reply



Submit