Android:检查我的应用程序是否允许运行后台活动

2024-03-22

我有一个运行秒表服务的应用程序,并且我在前台运行该服务。
我有一个显示计时器的通知,每秒更新一次。
在我离开应用程序 30 秒后,通知停止更新,我发现原因是我的设备的电池优化:
在我的应用程序的系统设置中,有一个电池优化部分,其中包含一个名为Allow background activity,可以打开或关闭。
我找到了 2 个线程(回答主题 1 https://stackoverflow.com/a/56047564/8099601 and 对话题 2 的回答 https://stackoverflow.com/a/66183449/8099601)试图回答如何检查设置的状态,他们都建议使用ActivityManager.isBackgroundRestricted.
对我来说,它不起作用。无论设置是打开还是关闭,该函数都会返回false.
我怎么能够检查我的应用程序是否允许运行后台活动?

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


我发现它对我也不起作用。因此,您可以在我的 Git 存储库中看到我的两个类,我也在其中提供了它们我之前的回答 https://stackoverflow.com/questions/71758160/android-notification-shows-in-delay-and-stops-updating-when-app-closed-for-30-s/71840843#71840843。我的回购链接也是here https://github.com/sambhav2358/Backgroud-Stopwatch-Android。这里你必须看到this https://github.com/sambhav2358/Backgroud-Stopwatch-Android/blob/f4db90771047fbc99bff3e07a3ed888758230f5e/Stop%20watch/app/src/main/AndroidManifest.xml#L6 in my AndroidManifest.xml and this https://github.com/sambhav2358/Backgroud-Stopwatch-Android/blob/f4db90771047fbc99bff3e07a3ed888758230f5e/Stop%20watch/app/src/main/java/com/sambhav2358/testing/MainActivity.java#L87方法和this https://github.com/sambhav2358/Backgroud-Stopwatch-Android/blob/f4db90771047fbc99bff3e07a3ed888758230f5e/Stop%20watch/app/src/main/java/com/sambhav2358/testing/MainActivity.java#L148重写的方法。

我在那里请求忽略电池优化权限,如果启用它,它工作正常,或者如果未启用,则请求该权限。

此外,您还可以查看与以下内容相关的结果this https://stackoverflow.com/q/71758160/17133283问题的答案。This https://www.veed.io/view/f2160914-e6a9-41c6-88d5-0cb00bf0109d是结果


如果还是不行,请参考这段代码:

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

并将用户带到此设置的页面,基于这个答案 https://stackoverflow.com/a/49098293/8099601:

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))      
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android:检查我的应用程序是否允许运行后台活动 的相关文章

随机推荐