我发现它对我也不起作用。因此,您可以在我的 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))