onTaskRemoved() not getting called in HUAWEI and XIAOMI devices

Solution 1:

On some devices (some LG, Huawei, Xiaomi, and others) your app needs to be manually added to a list of "protected apps" or "apps that are allowed to run in the background" in order for Android to restart STICKY services. If your app has not been manually added to this list, Android just kills your processes and does not restart them and also does not call onTaskRemoved(). This is done to preserve battery life by limiting the number of apps that can have STICKY services running in the background.

On such devices you should see a page in the "Settings", sometimes under "power management", sometimes other places, where you need to explicitly add your application. You'll also need to tell your users to explicitly add your app to this list.

Solution 2:

When user has installed your app on xiaomi device, redirect user to auto start activity and tell user to switch on:

if (Build.BRAND.equalsIgnoreCase("xiaomi")) {
                Intent intent = new Intent();
                intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
                startActivity(intent);
            }

Use the above code to launch autostart activity page on xiaomi