Directly on the example, see how to avoid crash.
Eg: Gets the total space size of the partition on which this path resides, based on the given path.
Document Description: To obtain the file system usage, in the API level 9 and above the system, you can directly invoke File
the relevant methods of the object, the following need to calculate their own
API level 9 and above, File.getTotalSpace()
can be called, but the system object below API Level 8 File
does not exist for this method
As follows
/** * Returns the total size in bytes of the Partition containing this path. * Returns 0 If this path does not exist. * * @param path * @return */ public static long Gettotalspace (File path) { if (Path = = Span style= "color: #0000ff;" >null return -1; return Path.gettotalspace ();}
If minSdkVersion
set to 8, then the build will report the following error:
Call requires API level 9 (current min is 8)
In order to compile can pass, can add @SuppressLint("NewApi")
or @TargeApi(9)
.
@TargeApi($API_LEVEL)
the API level required to explicitly indicate the method, but not @SuppressLint("NewApi")
;
But this only can be compiled through, to the API Level8 system run, will be thrown java.lang.NoSuchMethodError
.
The right approach
In order to run without error, you need:
- Determine the runtime version, this method is not called in the low-version system
In order to ensure the integrity of the function, we need to provide the low-version function
As follows:
/*** Returns The total size in bytes of the partition containing this path. * Returns 0 If this path is does not exist. * * @paramPath *@return-1 means path is NULL, and 0 means path is not exist.*/@TargetApi (build.version_codes. Gingerbread)//using @TargeApi instead of @SuppressLint ("Newapi")@SuppressWarnings ("Deprecation") Public Static Longgettotalspace (File path) {if(Path = =NULL) { return-1; } if(Build.VERSION.SDK_INT >=Build.version_codes. Gingerbread) {returnPath.gettotalspace (); } //implements Gettotalspace () in API lower than gingerbread Else { if(!path.exists ()) { return0; } Else { FinalStatFs stats =NewStatFs (Path.getpath ()); //Using deprecated method in the low API level system,//Add @SuppressWarnings ("description") to suppress the warning return(Long) Stats.getblocksize () * (Long) Stats.getblockcount (); } }}
Summarize:
- Use to
@TargeApi($API_LEVEL)
make can be compiled through, not recommended @SuppressLint("NewApi")
;
- Run-time judgment API level; This method is called only in an API level system that is high enough to have this method;
- Ensure functional integrity and ensure that low API versions provide functionality through other methods.
Compatibility of High version API in low version