我有一个运行秒表服务的应用程序,我在前台运行这个服务。
我有一个显示计时器的通知,它每秒钟更新一次。
在我离开应用程序30秒后通知停止更新,我发现原因是我的设备的电池优化:
在我的应用程序的系统设置中,有一个电池优化部分,其中包含一个名为Allow background activity
的设置,可以打开也可以关闭。
我发现两个线程(对线程1的回答和对线程2的答复)试图回答如何检查设置的状态,这两个线程都建议使用ActivityManager.isBackgroundRestricted
。
但对我来说,这没什么用。无论设置是打开还是关闭,此函数都返回false
。
如何检查我的应用程序是否允许运行后台活动?
下面是我手机中设置的一张照片(OnePlus 8t OxygenOS 12):
发布于 2022-04-14 04:52:04
我看它对我也不管用。因此,您可以在我的Git中看到我的两个类,这也是我在我先前的回答中提供给您的。另外,我的回购链接是这里。在这里,您必须在我的AndroidManifest.xml
和这方法以及这重写方法中看到这。
在那里,我要求忽略电池优化权限,如果它是启用的,它工作良好,如果没有启用,请求该权限。
如果这不起作用,请参考以下代码:
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.
}
并将用户带到此设置的页面,基于这个答案
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))
https://stackoverflow.com/questions/71865718
复制相似问题