首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Android:检查我的应用程序是否允许运行后台活动。

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

Stack Overflow用户
提问于 2022-04-14 02:12:15
回答 1查看 1.4K关注 0票数 0

我有一个运行秒表服务的应用程序,我在前台运行这个服务。

我有一个显示计时器的通知,它每秒钟更新一次。

在我离开应用程序30秒后通知停止更新,我发现原因是我的设备的电池优化:

在我的应用程序的系统设置中,有一个电池优化部分,其中包含一个名为Allow background activity的设置,可以打开也可以关闭。

我发现两个线程(对线程1的回答对线程2的答复)试图回答如何检查设置的状态,这两个线程都建议使用ActivityManager.isBackgroundRestricted

但对我来说,这没什么用。无论设置是打开还是关闭,此函数都返回false

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

下面是我手机中设置的一张照片(OnePlus 8t OxygenOS 12):

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-14 04:52:04

我看它对我也不管用。因此,您可以在我的Git中看到我的两个类,这也是我在我先前的回答中提供给您的。另外,我的回购链接是这里。在这里,您必须在我的AndroidManifest.xml方法以及重写方法中看到

在那里,我要求忽略电池优化权限,如果它是启用的,它工作良好,如果没有启用,请求该权限。

此外,您还可以查看与问题的答案相关的结果。是结果

如果这不起作用,请参考以下代码:

代码语言:javascript
运行
复制
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.
}

并将用户带到此设置的页面,基于这个答案

代码语言:javascript
运行
复制
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))      
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71865718

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档