Prevent API level warning in code

I'm trying to create the intention to create SMS with compatibility for API levels above KitKat . The code works, but I got a warning that API level 19 is required. I tried to enable it with @TargetApi(Build.VERSION_CODES.KITKAT) , but I got the warning " Annotations are not allowed here."

Is there an easy way to ignore this warning?

 private boolean apLowerThanKitKat = (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT); Intent smsIntent = new Intent(android.content.Intent.ACTION_SEND); if (apLowerThanKitKat) { smsIntent.setPackage("vnd.android-dir/mms-sms"); } else { //@TargetApi(Build.VERSION_CODES.KITKAT) smsIntent.setPackage(Telephony.Sms.getDefaultSmsPackage(getActivity())); } 

Thanks in advance!

+6
source share
4 answers

Do not use a boolean to validate the API. Place it directly in the if statement:

 if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) { smsIntent.setPackage("vnd.android-dir/mms-sms"); } else { smsIntent.setPackage(Telephony.Sms.getDefaultSmsPackage(getActivity())); } 

This should make the warning go away. TargetApi annotations must be run at the method level:

 @TargetApi(Build.VERSION_CODES.KITKAT) public void yourKitkatMethod() {} 
+9
source

Annotations must be done by method

 private boolean apLowerThanKitKat = (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT); Intent smsIntent = new Intent(android.content.Intent.ACTION_SEND); if (apLowerThanKitKat) { smsIntent.setPackage("vnd.android-dir/mms-sms"); } else { kitkatSetPackage(): } @TargetApi(Build.VERSION_CODES.KITKAT) private void kitkatSetPackage() { smsIntent.setPackage(Telephony.Sms.getDefaultSmsPackage(getActivity())); } 

You can transfer this annotation to other methods (if all this code is in one method) or put the annotation into the class itself.

+4
source

I’m constantly moving from version to version in AOSP, and I don’t want to mislead the next person reading my code with specific annotation of @TargetApi() version. So you can do the following:

 @SuppressLint("NewApi") public void xyzMethod() { <your_code> ... } 
0
source

** Put your code in a method **

 @TargetApi(Build.VERSION_CODES.KITKAT) public void xyzMethod(){ your code here } 

it will work now

-1
source

Source: https://habr.com/ru/post/1239491/


All Articles