How to Handle Compatibility of Android High Version API Method on Low Version System
- 2021-10-13 08:38:28
- OfStack
Preface
In the recent development, we need to obtain the network status of SIM card, and see 1 method in the source code:
TelephonyManager tm =(TelephonyManager)context.getSystemService(TELEPHONY_SERVICE);
state =tm.getDataNetworkType();
But there was an error
Call requires API level 24 (current min is 21): android.telephony.TelephonyManager#getDataNetworkType
Android version changes, the new version brings new features, new methods.
The new method brings a lot of convenience, but it can't run on a lower version system. If the compatibility is not handled properly, APP will run on a lower version system and crash will run.
Treatment method
Step 1 Add
@RequiresApi(api = Build.VERSION_CODES.N)
Step 2 Add
@TargetApi(Build.VERSION_CODES.N)
Step 3 Add
@SuppressLint("NewApi")
4. Add runtime SDK version judgment
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
tm.getDataNetworkType();
}
5. Implement this functionality in a lower version by other means
Summarize
Methods 1. 2. 3 just compile through, and when a system below API24 runs, it will throw
java.lang.NoSuchMethodError
.
The correct way is to add a runtime SDK version judgment, and add other methods to realize this function when it is judged to be a lower version