Compatibility processing of Android high version API methods on low version systems
Android version replacement, the new version brings new features and new methods.
The new method brings many conveniences, but it cannot run on the lower version system. If the compatibility processing is not appropriate, the app will crash when running on the lower version system.
This paper uses a specific example to illustrate how to deal with the compatibility problem when using high API level methods.
Example: obtain the total space size of the partition where the path is located according to the given path.
In the document storage and use reference in Android, it is mentioned that:
Get the usage of the file system. In systems with API level 9 and above, you can directly call the relevant methods of the file object. The following needs to be calculated by yourself
General implementation
For this requirement, API level 9 and above call file Gettotalspace() is OK, but this method does not exist in the system file object below API level 8.
As follows:
Processing failed to compile
If minsdkversion is set to 8, the following error will be reported during build:
Call requires API level 9 (current min is 8)
To compile, you can add @ suppresslint ("newapi") or @ targeapi (9).
Use @ targeapi ($api_level) to explicitly indicate the API level requirements of the method, rather than @ suppresslint ("newapi");
However, it can only be compiled. When the API level 8 system runs, it will trigger Java lang.NoSuchMethodError。
Right approach
In order not to report errors during operation, you need to:
Judge the runtime version. This method is not called in the low version system. At the same time, in order to ensure the integrity of the function, it is necessary to provide the low version function implementation
As follows:
summary
When using methods higher than the minsdkversion API level, you need to:
I hope this article can help you solve the API compatibility problem of Android version! Thank you for your support!