1, the introduction

For developers of mobile IM and push apps, the Android backend is all too familiar.

Since the introduction of Android P (Android 8.0), Android has blocked the way to keep the background alive at the system level (see: Android P official release coming soon: “The real nightmare of the Backend application, the Real nightmare of the news push”), and the ever-emerging technology of the backend protection is becoming less and less useful (see “The Real Effect of the Current Android Backend Protection Scheme (by 2019)”. Although it can connect to the room-level push channel of the manufacturer by itself, on the one hand, the push interfaces of different manufacturers are different (and there are compatibility problems of push interfaces between different system versions of the same manufacturer), which is very inconvenient. On the other hand, introducing their own push service SDK packages will make the APP very large, which makes the APP download very unfriendly.

All in all, there is an ongoing need to keep Android applications alive in the background in some scenarios. What other ways can we save lives in the era of Android 9.0 (or even Android 10), beyond the more familiar hacks of the past? Follow the author’s lead on a more elegant implementation of backend preservation.

(This article is simultaneously published at: www.52im.net/thread-2881…)

2. About the author

Net name NanBox: GRADUATED from Huazhong University of Science and Technology, now I am a senior Android development engineer of “Yuehuanhuan APP”. Mainly responsible for the development of the company’s Android project and core modules. Involves GPS positioning, map, picture editing and other functions. Independently developed the watch application project. The cross-platform development technology of Flutter was included in the project, realizing the mixed development of native and Flutter.

The author of this article is willing to share, and usually writes technical articles and shares them on multiple platforms. As a member of the nuggets columnist, his articles have been read more than 100,000 times. There are multiple open source projects on GitHub and many times technology sharing within the team. Flutter is the official Chinese document translator for Android and Flutter.

3. Related articles

If you want to learn more about the current challenges of backend preservation on Android, read:

Android P official coming soon: The real nightmare of app survival and push notifications.

If you want to look back at some of the best Android technologies ever, here’s a good read:

A Comprehensive Review of the real Operation Effect of the Current Android Background Preservation Scheme (by 2019)

“Application survival (1) : dual-process daemon survival practices under Android6.0”

Android6.0 and above (process prevention)

Android6.0 and above survival practices (killed and resurrected)

How to Keep the Android Process Alive: One Article to Solve All Your Questions

Summary of Message Push on Android: Implementation principle, Heartbeat Survival, Problems encountered, etc.

An in-depth look at the Little Matter of Android News Push

Why Does TCP – based MOBILE IM Still Need heartbeat Keepalive mechanism?

“Wechat Team original Sharing: Android version of wechat background Survival combat Sharing (Process survival)”

“Sharing of Rongyun Technology: Practice of Network Link Preservation Technology of Rongyun Android IM Products”

4. Android keeps the status quo

We know that background processes can be killed on Android, and this is likely to get worse as the system updates (see Android P official coming soon: Background Application survival, real Nightmare of Push notifications).

System this approach itself is good, because you can save memory, reduce power consumption, but also to avoid some rogue behavior.

However, some applications need to be run in the background for the application itself, and users are willing to let it run in the background, such as running applications, IM applications that are too lazy to connect with manufacturers’ push channels, and message push information applications.

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.

5, elegant survival?

In order to do this, there are a lot of “black technology”, such as 1 pixel Activity, playing silent audio, dual process guard each other, etc. (can read this series: “Application protection ultimate summary (1) : Android6.0 and above live practice (process anti-kill), “application live final summary (three) : Android6.0 and above live practice (killed resurrected)”).

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?

6, join the white list of background operation, can be elegant to achieve survival

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 by the application in the whitelist. In the native system, you can view the whitelist by clicking “Settings” – “Battery” – “Battery Optimization” – “Not optimized Application”.

You’ll usually 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-permissionandroid:name=”android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS”/>

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;

}

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 = newIntent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);

        intent.setData(Uri.parse(“package:”+ getPackageName()));

        startActivity(intent);

    } catch(Exception e) {

        e.printStackTrace();

    }

}

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.

7. Add the multi-vendor adaptation method to the background whitelist

7.1 Basic Information

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:

/ * *

* Jump to the home page of the specified application

* /

private void showActivity(@NonNull String packageName) {

    Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);

    startActivity(intent);

}

 

/ * *

* Jumps to the specified page for the specified application

* /

private void showActivity(@NonNull String packageName, @NonNull String activityDir) {

    Intent intent = new Intent();

    intent.setComponent(newComponentName(packageName, activityDir));

    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    startActivity(intent);

}

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.

7.2 huawei

Manufacturer judgment:

public boolean isHuawei() {

    if(Build.BRAND == null) {

        return false;

    } else{

        return Build.BRAND.toLowerCase().equals(“huawei”) || Build.BRAND.toLowerCase().equals(“honor”);

    }

}

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”);

    }

}

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

7.3 millet

Manufacturer judgment:

public static boolean isXiaomi() {

return Build.BRAND ! = null&& Build.BRAND.toLowerCase().equals(“xiaomi”);

}

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

private void goXiaomiSetting() {

    showActivity(“com.miui.securitycenter”,

        “com.miui.permcenter.autostart.AutoStartManagementActivity”);

}

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

7.4 OPPO

Manufacturer judgment:

public static boolean isOPPO() {

return Build.BRAND ! = null&& Build.BRAND.toLowerCase().equals(“oppo”);

}

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”);

            }

        }

    }

}

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

7.5 VIVO

Manufacturer judgment:

public static boolean isVIVO() {

return Build.BRAND ! = null&& Build.BRAND.toLowerCase().equals(“vivo”);

}

Jump VIVO mobile phone butler:

private void goVIVOSetting() {

    showActivity(“com.iqoo.secure”);

}

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

7.6 the meizu

Manufacturer judgment:

public static boolean isMeizu() {

return Build.BRAND ! = null&& Build.BRAND.toLowerCase().equals(“meizu”);

}

Jump to Meizu mobile phone butler:

private void goMeizuSetting() {

    showActivity(“com.meizu.safe”);

}

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

7.7 samsung

Manufacturer judgment:

public static boolean isSamsung() {

return Build.BRAND ! = null&& Build.BRAND.toLowerCase().equals(“samsung”);

}

Jump to Samsung Smart Manager:

private void goSamsungSetting() {

    try{

        showActivity(“com.samsung.android.sm_cn”);

    } catch(Exception e) {

        showActivity(“com.samsung.android.sm”);

    }

}

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

7.8 Letv

Manufacturer judgment:

public static boolean isLeTV() {

return Build.BRAND ! = null&& Build.BRAND.toLowerCase().equals(“letv”);

}

Jump leEco mobile phone butler:

private void goLetvSetting() {

    showActivity(“com.letv.android.letvsafe”,

        “com.letv.android.letvsafe.AutobootManageActivity”);

}

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

7.9 the hammer

Manufacturer judgment:

public static boolean isSmartisan() {

return Build.BRAND ! = null&& Build.BRAND.toLowerCase().equals(“smartisan”);

}

Jump to mobile phone management:

private void goSmartisanSetting() {

    showActivity(“com.smartisanos.security”);

}

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

8, friends business salute?

In the running app I created earlier, I added a permission page to my Settings and put the Settings mentioned above in it.

Recently, it was found that a friend dong also followed up. Figure 1 is what we did, and Figure 2 is what Dong did:

Some dong from the design, from my writing is not good enough copy, and even I from a dozen phones on a cut down the picture, for a full range of tribute. Thanks to some dong’s recognition, but recently in a release conference heard such a sentence: in salute at the same time, can you say thank you?

Some dong salute, on the one hand, shows that there is indeed a process is easy to kill, the difficulty of keeping alive the problem, on the other hand, also shows that this kind of guide users to white list Settings means is effective.

Appendix: More technical articles

“Application survival (1) : dual-process daemon survival practices under Android6.0”

Android6.0 and above (process prevention)

Android6.0 and above survival practices (killed and resurrected)

How to Keep the Android Process Alive: One Article to Solve All Your Questions

Summary of Message Push on Android: Implementation principle, Heartbeat Survival, Problems encountered, etc.

An in-depth look at the Little Matter of Android News Push

Why Does TCP – based MOBILE IM Still Need heartbeat Keepalive mechanism?

“Wechat Team original Sharing: Android version of wechat background Survival combat Sharing (Process survival)”

“Wechat team original sharing: Android version of wechat backstage Combat Sharing (Network Protection)”

Mobile IM Practice: Implementing intelligent Heartbeat Mechanism of wechat on Android

Mobile IM Practice: Analysis of Heartbeat Strategy of WhatsApp, Line and wechat

Android P is coming soon: The Real Nightmare of Backend Apps and Notifications

A Comprehensive Review of the real Operation Effect of the Current Android Background Preservation Scheme (by 2019)

Understanding the Mechanism of Network Heartbeat Packet in Instant Messaging Applications: Functions, Principles, Implementation ideas, etc.

“Sharing of Rongyun Technology: Practice of Network Link Preservation Technology of Rongyun Android IM Products”

“Correctly understand the IM long connection heartbeat and reconnection mechanism, and start to implement (complete IM source code)”

In 2020, Android backstage survival is still a play? See how I elegantly implement!

>> More similar articles……

(This article is simultaneously published at: www.52im.net/thread-2881…)