First of all, this may be a very rare optimization, but we still spent a lot of time and effort figuring out the nitty-gritty of this optimization, so I thought it made sense to share this little optimization. Looking forward to the day when someone, somewhere, may encounter the same problem and benefit from this article.

What is reflection?

Reflection is used to observe and modify the behavior of a program at run time. A reflection-oriented program component can monitor code execution in a range and modify itself based on the information obtained about the target object and the range associated with it. This is achieved by dynamically distributing program code at run time.

In object-oriented programming languages with strict type detection such as Java, it is generally necessary to check the validity of the specific types, interfaces, data members and methods of objects to be called in the program during compilation. Reflection technology allows you to defer message checking on the object to be invoked from compile time to run time and then perform it in the field.

In this way, interface names, fields fields (data members (member variables) of objects) and available methods of the target object can be undefined during compilation, and then processing can be decided at run time based on the messages of the target object itself. It also allows you to instantiate new objects and call related methods based on the judgment results.

Why is this a problem?

We have been receiving complaints that our Buzz widget is lagging on the Redmi Note 5 after the dynamic wallpaper is enabled. To reproduce this problem, we used Umeng +U-APM to run an online test on Redmi Note 5, while using a custom exception to throw the problem.

Tests show that the exception is through WallpaperManager getInstance (this). GetWallpaperInfo triggered the if () code, that is to say, this is due to the application of fuzzy desktop, and attempt to render content leads to problems on the surface of the table. If you have a live wallpaper running on your desktop, blurring it can cause some periodic processor consumption.

Why use reflection instead of an API?

I would prefer to have only one version of each of our apps in the Android Market, and the API for this is only available in part of the SDK. Reflection allows us to use the API while still letting the application run on devices with older firmware.

How to solve it?

Okay, we’re going to show you the solution

if(WallpaperManager.getInstance(this).getWallpaperInfo() ! = null){// unambiguous}

To use reflection to do this, we must use the class.forname (“”), class.getDeclaredMethod (), and Object.invoke() methods, something like this:

Also to ensure a secure call, we wrapped it in a quick Android version check and a try/catch block to ensure security: That’s it. Now, if the device has a live wallpaper, the application background won’t be blurred, and our Widget World will be back to normal.

Author: Dai Meiling