Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to only execute code on certain API level

Tags:

android

For instance, this code:

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {

  myCalendarView.setOnDateChangeListener(
    new OnDateChangeListener() {

      @Override
      public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
        Toast.makeText
        (
          getApplicationContext(), ""+dayOfMonth, 0
        ).show();        
      }

    }
  );

}  

Gives error:

Description Resource Path Location Type Call requires API level 11 (current min is 8): android.widget.CalendarView#setOnDateChangeListener example.java /example/src/com/example/example line 20 Android Lint Problem

I understand why I get this error compile-time. But is there any way to mark a source Java class to only be used on certain API level-11? Or surround code blocks with a define/similar so the code is late-bound/jitted only on devices above API level-11? What is the best solution to achieve what I want? (Which is to provide an activity with CalendarView on devices capabile of it.)

like image 314
Tom Avatar asked Mar 19 '13 14:03

Tom


People also ask

What is the minimum required sdk API level?

For more information about downloading and installing Android SDK components, see Android SDK Setup. Beginning in August 2021, the Google Play Console requires that new apps target API level 30 (Android 11.0) or higher. Existing apps are required to target API level 30 or higher beginning in November 2021.

What is API level?

API Level is an integer value that uniquely identifies the framework API revision offered by a version of the Android platform. The Android platform provides a framework API that applications can use to interact with the underlying Android system. The framework API consists of: A core set of packages and classes.

What is the difference between compileSdkVersion and targetSdkVersion?

Even if the compileSdkVersion and targetSdkVersion have completely different meanings they are obviously not independent. targetSdkVersion cannot be higher than the compileSdkVersion simply because we cannot target things that we know nothing about during compilation.

What API level should I develop for?

New apps must target Android 12 (API level 31) or higher; except for Wear OS apps, which must target Android 11 (API level 30) or higher.


1 Answers

I'm not sure if this is going to solve your issue,

but what you are using to check version is not working under API 9 (and you are supporting since API 8).

You should use:

if (Build.VERSION.SDK_INT > 9) { 

Or as problematic function is API 11, check for "SDK_INT>10"

Then for lint errors on eclipse, do as people comment, disable lint errors or add the @SuppressLint("NewAPi") or the target to that function to 11.

like image 98
Darklord5 Avatar answered Oct 22 '22 15:10

Darklord5