Android background running whitelist, elegant implementation of survival

Keep alive the status quo

As we know, the Android system will have the situation of killing background processes, and with the update of the system version, there is a trend of killing processes more and more. System this approach itself is good, because you can save memory, reduce power consumption, but also to avoid some rogue behavior.

But there are some applications where the application itself needs to run in the background, and users are willing to let it run in the background, such as running apps. On the one hand, rogue software with a variety of rogue means to keep alive, on the other hand, the system to increase the strength of killing background, leading to some of our real need to run in the background of the application was mistakenly killed, suffering unspeakable.

Grace for life?

In order to do this, there are a lot of “black technology”, such as 1 pixel Activity, playing silent audio, two processes guard each other and so on. These practices can be said to be rogue, and even destroy the Android ecosystem, fortunately, with the release of the Android system, many of these unconventional survival measures have been ineffective.

For applications that really need to run in the background, how do we keep them alive gracefully?

Background running whitelist

Since Android 6.0, the system has added hibernation mode to save power. After the system is in standby mode for a period of time, it will kill the background processes that are running. However, the system will have a background running whitelist, which will not be affected. In the native system, you can view this whitelist by clicking “Settings” – “Battery” – “Battery Optimization” – “Unoptimized Application”, usually you will see the following two:

The next time the product says “XXX can keep alive, why can’t we!” “You’ll know how to fight back. Big manufacturers have their apps whitelisted by default through partnerships with handset manufacturers. If you are in a big factory where such a deal can be negotiated, look no further.

Fortunately, the system hasn’t abandoned us and allowed us to apply for whitelisting.

First, configure the permissions in the Androidmanifest.xml file:

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

You can use the following methods to determine whether our application is in the whitelist:

@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;
}
Copy the code

If you are not in the whitelist, you can apply to be added to the whitelist by using 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(); }}Copy the code

When you apply, the app will display a window like this:

As you can see, the system pops up with reminders that affect battery life, so if you want the user to click “allow”, you must have the relevant instructions. To determine whether the user clicked “Allow”, you can call startActivityForResult at the time of the request, and check whether the user is in the whitelist again in onActivityResult.

Vendor Background Management

One of the difficulties of Android development is that various mobile phone manufacturers have customized the native system differently, leading 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 running whitelist, it may still be eliminated by the manufacturer’s own background management.

If the application can be added to the whitelist of the vendor system’s background administration, the probability of process killing can be further reduced. Different vendors do this in different places, usually in their own “phone managers,” but even harder, different versions of the same vendor’s system may be set up in different places.

Ideally, depending on the phone, or even the system version, we would present users with a graphical step and provide a button to go directly to the specified page for setting. But need to adapt to each manufacturer each version, workload is relatively large. After testing most of the major Android manufacturers on a real phone, I’ve sorted out some of them.

First we can define two methods:

Private void showActivity(@nonNULL String packageName) {Intent Intent = getPackageManager().getLaunchIntentForPackage(packageName); startActivity(intent); 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 judgment of some mobile phone manufacturers, the jump method and the corresponding setting steps. The jump method is not guaranteed to be able to jump successfully on all versions, and a try catch is required.

huawei

Manufacturer 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

Go to the startup management page of Huawei Mobile Phone Manager:

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"); }}Copy the code

Procedure: Manage application startup -> Disable application -> Enable Automatic startup

millet

Manufacturer judgment:

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

Jump to the page of self-start management of xiaomi Security Center:

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

Procedure: Authorization Management > Automatic Startup Management > Allow automatic startup of applications

OPPO

Manufacturer judgment:

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

Jump to OPPO mobile phone butler:

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"); }}}}Copy the code

Procedure: Permission Privacy > Automatic Startup Management > Allow Automatic Startup of applications

VIVO

Manufacturer judgment:

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

Jump VIVO mobile phone butler:

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

Procedure: Permission Management > Automatic Startup > Allow automatic startup of applications

meizu

Manufacturer judgment:

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

Jump to Meizu mobile phone butler:

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

Operation procedure: Permission Management -> Background Management -> Click Apply -> Allow Background running

samsung

Manufacturer judgment:

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

Jump to Samsung Smart Manager:

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

Operations: Automatically run applications -> Turn on applications -> Battery Management -> Unmonitored Applications -> Add Applications

Letv

Manufacturer judgment:

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

Jump leEco mobile phone butler:

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

Procedure: Automatic Startup Management -> Allow automatic startup of applications

The hammer

Manufacturer judgment:

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

Jump to mobile phone management:

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

Procedure: Permission management -> Self-start Permission management -> Apply -> Allow To be started

Original link: juejin.cn/post/684490…