Android Min SDK Version vs. Target SDK Version

后端 未结 9 950
别那么骄傲
别那么骄傲 2020-11-22 04:33

When it comes to developing applications for Android, what is the difference between Min and Target SDK version? Eclipse won\'t let me create a new project unless Min and Ta

9条回答
  •  悲哀的现实
    2020-11-22 05:18

    If you get some compile errors for example:

    
    

    .

    private void methodThatRequiresAPI11() {
            BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inPreferredConfig = Config.ARGB_8888;  // API Level 1          
                    options.inSampleSize = 8;    // API Level 1
                    options.inBitmap = bitmap;   // **API Level 11**
            //...
        }
    

    You get compile error:

    Field requires API level 11 (current min is 10): android.graphics.BitmapFactory$Options#inBitmap

    Since version 17 of Android Development Tools (ADT) there is one new and very useful annotation @TargetApi that can fix this very easily. Add it before the method that is enclosing the problematic declaration:

    @TargetApi
    private void methodThatRequiresAPI11() {            
      BitmapFactory.Options options = new BitmapFactory.Options();
          options.inPreferredConfig = Config.ARGB_8888;  // API Level 1          
          options.inSampleSize = 8;    // API Level 1
    
          // This will avoid exception NoSuchFieldError (or NoSuchMethodError) at runtime. 
          if (Integer.valueOf(android.os.Build.VERSION.SDK) >= android.os.Build.VERSION_CODES.HONEYCOMB) {
            options.inBitmap = bitmap;   // **API Level 11**
                //...
          }
        }
    

    No compile errors now and it will run !

    EDIT: This will result in runtime error on API level lower than 11. On 11 or higher it will run without problems. So you must be sure you call this method on an execution path guarded by version check. TargetApi just allows you to compile it but you run it on your own risk.

提交回复
热议问题