Android:检查我的应用程序是否可以运行背景活动
我有一个运行秒表服务的应用程序,然后在前景中运行该服务。
我有一个通知显示计时器,每秒更新。
该通知在我离开应用程序后停止更新30秒,我发现原因是我的设备的电池优化:
在我应用程序的系统设置中,有一个电池优化部分,其中包含一个称为的设置允许背景活动
,可以打开或关闭。
我找到了2个线程(对线程1 和对线程2的答案)试图回答如何检查设置状态,并且两者都建议使用activitymanager.isbackgroundrestricter
。
对我来说,它不起作用。设置是打开还是关闭,此功能返回false
。
如何检查我的应用程序是否可以运行背景活动?
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):
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我看到它也对我不起作用。因此,您可以在我的git回购中看到我的两个课程更新贴上应用-30-S/71840843#71840843“>我以前的答案。另外,我的回购链接是在这里。 Here you must see
在那里,我要求忽略电池优化许可,如果启用了电池,则可以正常工作或不启用,请征得该许可。
此外,您可以查看与 this 问题的答案的结果。
该代码:
并将用户带到此设置页面,基于此答案:
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:
And to take the user to this setting's page, based on this answer: