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:
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.
}
And to take the user to this setting's page, based on this answer:
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))