Android background running white list, elegant realization of keeping alive

Original address https://juejin.cn/post/6844904023955341319
Living status
We know that the Android system will kill the background process, and with the update of the system version, the intensity of killing the process is still increasing. The starting point of the system itself is good, because it can save memory, reduce power consumption and avoid some rogue behavior.
However, for some applications, the use scenarios of the application itself need to run in the background, and users are willing to let it run in the background, such as running applications. On the one hand, rogue software is kept alive by various rogue means. On the other hand, the system strengthens the killing of the background, resulting in the accidental killing of some applications that really need to run in the background.
Elegant keep alive?
In order to keep alive, there have been many "black technologies", such as one pixel Activity, playing silent audio, two processes guarding each other, etc. These practices can be said to be very rogue and even destroy the ecology of Android. Fortunately, with the update of the Android system version, many of these unconventional means of keeping alive have failed.
For those applications that really need to run in the background, how can we keep them alive gracefully?
Background running whitelist
Since Android 6.0, the system has added sleep mode to save power. After the system is standby for a period of time, it will kill the running process in the background. However, the system will have a white list running in the background, and the applications in the white list will not be affected. In the native system, you can see the white list through "Settings" - "battery" - "battery optimization" - "non optimized applications". Usually, you can see the following two characters:

Next time the product says, "XXX can be kept alive, why can't we!" You'll know how to get back. Through cooperation with mobile phone manufacturers, large manufacturers add their applications to the white list by default. If you are in a big factory where such cooperation can be negotiated, you don't have to look down.
Fortunately, the system has not abandoned us and allowed us to apply for adding applications to the white list.
First, at Android manifest Configure the following permissions in the XML file:

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

Copying code can determine whether our application is in the white list by the following methods:

@RequiresApi(api = Build.VERSION_CODES.M)
private boolean isIgnoringBatteryOptimizations() {
    boolean isIgnoring = false;
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (powerManager != null) {
        isIgnoring = powerManager.isIgnoringBatteryOptimizations(getPackageName());
    }
    return isIgnoring;
}

If the copied code is not in the white list, you can apply to join the white list through the following code:

@RequiresApi(api = Build.VERSION_CODES.M)
public void requestIgnoreBatteryOptimizations() {
    try {
        Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

When copying the code application, a window will appear on the application:

It can be seen that the pop-up window of this system will have a reminder affecting the battery life, so if you want the user to click allow, you must have relevant instructions. If you want to judge whether the user has clicked allow, you can call startActivityForResult when applying, and judge whether it is in the white list again in onActivityResult.
Manufacturer background management
A difficulty in Android development is that major mobile phone manufacturers have customized the native system differently, which leads to different adaptations. Background management is a good embodiment. Almost every manufacturer has its own background management. Even if the application is added to the background operation white list, it may still be killed by the manufacturer's own background management.
If the application can be added to the background management white list of the manufacturer's system, the probability of process being killed can be further reduced. Different manufacturers set up in different places, usually in their own "mobile housekeeper", but what is more difficult is that even if the system of the same manufacturer, different versions may be set up in different places.
The best way is to present users with a graphic operation step according to different mobile phones or even different system versions, and provide a button to directly jump to the specified page for setting. However, each version of each manufacturer needs to be adapted, and the workload is relatively large. After testing the mobile phones of most mainstream Android manufacturers with real machines, I sorted out the relevant data of some mobile phones.
First, we can define two methods:

/**
 * Jump to the home page of the specified application
 */
private void showActivity(@NonNull String packageName) {
    Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
    startActivity(intent);
}
/**
 * Jump to the specified page of the specified application
 */
private void showActivity(@NonNull String packageName, @NonNull String activityDir) {
    Intent intent = new Intent();
    intent.setComponent(new ComponentName(packageName, activityDir));
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

Copy the code. The following is the manufacturer's judgment, jump method and corresponding setting steps of some mobile phones. The jump method does not guarantee successful jump on all versions, and try catch needs to be added.
Huawei
Manufacturer's judgment:

public boolean isHuawei() {
    if (Build.BRAND == null) {
        return false;
    } else {
        return Build.BRAND.toLowerCase().equals("huawei") || Build.BRAND.toLowerCase().equals("honor");
    }
}

Copy the code and jump to the startup management page of Huawei mobile housekeeper:

private void goHuaweiSetting() {
    try {
        showActivity("com.huawei.systemmanager",
            "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity");
    } catch (Exception e) {
        showActivity("com.huawei.systemmanager",
            "com.huawei.systemmanager.optimize.bootstart.BootStartActivity");
    }
}

Operation steps of copying Code: application startup management - > turn off Application Switch - > turn on allow self startup
millet
Manufacturer's judgment:

public static boolean isXiaomi() {
    return Build.BRAND != null && Build.BRAND.toLowerCase().equals("xiaomi");
}

Copy the code and jump to the self startup management page of Xiaomi security center:

private void goXiaomiSetting() {
    showActivity("com.miui.securitycenter",
        "com.miui.permcenter.autostart.AutoStartManagementActivity");
}

Operation steps of copying Code: authorization management - > self start management - > allow application self start
OPPO
Manufacturer's judgment:

public static boolean isOPPO() {
    return Build.BRAND != null && Build.BRAND.toLowerCase().equals("oppo");
}

Copy the code and jump to OPPO mobile housekeeper:

private void goOPPOSetting() {
    try {
        showActivity("com.coloros.phonemanager");
    } catch (Exception e1) {
        try {
            showActivity("com.oppo.safe");
        } catch (Exception e2) {
            try {
                showActivity("com.coloros.oppoguardelf");
            } catch (Exception e3) {
                showActivity("com.coloros.safecenter");
            }
        }
    }
}

Operation steps of copying Code: permission privacy - > self startup management - > allow application self startup
VIVO
Manufacturer's judgment:

public static boolean isVIVO() {
    return Build.BRAND != null && Build.BRAND.toLowerCase().equals("vivo");
}

Copy the code to jump to VIVO mobile housekeeper:

private void goVIVOSetting() {
    showActivity("com.iqoo.secure");
}

Operation steps of copying Code: permission management - > self startup - > allow application self startup
Meizu
Manufacturer's judgment:

public static boolean isMeizu() {
    return Build.BRAND != null && Build.BRAND.toLowerCase().equals("meizu");
}

Copy the code and jump to Meizu mobile housekeeper:

private void goMeizuSetting() {
    showActivity("com.meizu.safe");
}

Operation steps of copying Code: permission management - > background management - > Click application - > allow background operation
Samsung
Manufacturer's judgment:

public static boolean isSamsung() {
    return Build.BRAND != null && Build.BRAND.toLowerCase().equals("samsung");
}

Copy the code and jump to Samsung Intelligent Manager:

private void goSamsungSetting() {
    try {
        showActivity("com.samsung.android.sm_cn");
    } catch (Exception e) {
        showActivity("com.samsung.android.sm");
    }
}

Operation steps of copying Code: automatically run application - > turn on Application Switch - > battery management - > unmonitored application - > add application
letv
Manufacturer's judgment:

public static boolean isLeTV() {
    return Build.BRAND != null && Build.BRAND.toLowerCase().equals("letv");
}

Copy the code and jump to LETV mobile housekeeper:

private void goLetvSetting() {
    showActivity("com.letv.android.letvsafe", 
        "com.letv.android.letvsafe.AutobootManageActivity");
}

Operation steps of copying Code: self startup management - > allow application self startup
hammer
Manufacturer's judgment:

   public static boolean isSmartisan() {
        return Build.BRAND != null && Build.BRAND.toLowerCase().equals("smartisan");
    }

Copy code to jump to mobile phone management:

private void goSmartisanSetting() {
    showActivity("com.smartisanos.security");
}

Operation steps of copying Code: permission management - > self start permission management - > Click application - > allow to be started by the system

Keywords: Android

Added by tommynanda on Thu, 10 Feb 2022 11:02:56 +0200