Search code examples
javaandroidbuild.gradleandroid-camera2

How to use the camera2 class for API 21 and make the app still running for lower APIs?


I am a beginner in android development and I am having a problem with using android.hardware.camera2 due to that my minimum sdk is API 16. So what I want to do now is be able to use that class but at the same time I can still make sure that people who are using lower SDK can still use it.

Should I make the minimum SDK version into API 21 and just create an if else statement for the users who have a lower version? Or is there another way?

Update: I cannot import android.hardware.camera, so how I am going to use it in my if else statement (if it was the only option)?


Solution

  • You don't need minSdkVersion ≥ 21 to use camera2 API. You don't even need to set targetSdkVersion. All you need is that compileSdkVersion be ≥ 21 (it's good practice to use the latest API available at development time).

    Since your min API is > 4, you can simply use the new camera2 API in blocks under if (Build.VERSION.SDK_INT >= 21). This is the common accepted practice for Android, event though some software purists would insist on run-time checks for the presence of android.hardware.camera2.CameraManager class.

    You should isolate the code that uses the deprecated Camera API, and mark these methods with annotations @TargetApi(16) or @SuppressWarnings("deprecation").