Search code examples
javaandroidnotificationsbackground-serviceforeground-service

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


I have an app that runs a stopwatch service, and I run the service in the foreground.
I have a notification showing the timer, that updates each second.
The notification stops updating 30 seconds after I leave the app, and I figured out that the cause is my device's battery optimization:
Inside my app's system settings, there is a battery optimization section, that contains a setting called Allow background activity, which can be on or off.
I found 2 threads (answer to thread 1 and answer to thread 2) trying to answer how to check the setting's state, and both of them suggest using ActivityManager.isBackgroundRestricted.
For me, it didn't work though. Whether the setting was switched On or Off, this function returned false.
How can I check if my app is allowed to run background activities?

Here's a photo of the setting in my phone (OnePlus 8t OxygenOS 12): system settings of my app


Solution

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