Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

Conditionally compile Android Java import statements

How can the import section of an Android Java program be conditionally compiled? I know we can conditionally compile classes in Java code using @TargetApi(). However, @TargetApi() does not work for the import section at the top of the java file.

In particular, I want to be able to ignore these import statement when compiling with compileSdkVersion and targetSdkVersion of 27. However, I want to keep these statements in the code and compile them when compileSdkVersion and targetSdkVersion are 30, or above. I wish the following code worked, but does not. Any suggestions?:

@TargetApi(30) // <== This statement does not work in this section, alternatives?
import android.net.wifi.WifiNetworkSuggestion
import static android.provider.Settings.ACTION_WIFI_ADD_NETWORKS;
import static android.provider.Settings.EXTRA_WIFI_NETWORK_LIST;
question from:https://stackoverflow.com/questions/65846423/conditionally-compile-android-java-import-statements

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As CommonsWare mentioned, using compileSdkVersion of 30, all the time, is correct in my circumstance. Also, surrounding particular classes with @RequiresApi(api = Build.VERSION_CODES.R) and obtaining the target SDK version with packageInfo.applicationInfo.targetSdkVersion (see https://stackoverflow.com/a/30353224/3179186) satisfied my requirements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...