How to handle build API version > minSdkVersion? - android

my app has minSdkVersion = 8, targetSdkVersion = 15 and SDK build version = 8. In general it works well, including on ICS but I would like to provide few more features to ICS users, for example resizeable widgets. This requires increasing also the SDK build version to 15.
I am concerned about the API static safety. For example if I will use unintentionally an API features that is not available on old phones.
What are good practices to handle SDK build version > minSdkVersion? How can I verify before shipping a new version that it does not break on old phones? What are good practices to address it?

I don't know if this is considered "good practise", but I just open the file project.properties and change the property target=android-11 to whatever API level I want to check. Once the file is saved, Eclipse will starting flagging errors where the API calls above the set version are. I just scan through them, check that they're encompassed by API-level checks, and then change the property back.

I tried Glitch's answer (thanks!), it kind of works but not as I expected. My widget info files have API 15 attributes such as
android:minResizeWidth="40dp"
android:minResizeHeight="40dp"
android:resizeMode="horizontal|vertical"
When I change the SDK build version from 15 to 8, these lines are flagged at error (which is fine) which fail the generation of the R class. This in turn flags every reference to R as an error (hundrads). Now, if I have something like
someApi15SpecificMethod(R.xyz)
Since the argument is undefined, it cannot tell safely if someApi15SpecificMethod(...) exists in API 8.
Since Glitch's answer is the best so far I am flagging it at the answer but please keep posting ideas here.

Related

Android: How can sharedUserId(deprecated in API level 29) be safely removed from an app?

I am dealing with an app that has android:sharedUserId value in Manifest,
and there was an issue regarding permission triggered by this android:sharedUserId value.
While trying to solve the problem, I checked out that anderoid:sharedUserId was deprecated in API level 29 (Android 10).
So now I would really like to remove this sharedUserId from the application. (permission problem in API 29 + deprecated in API 29)
As I tested in debug mode, it seems that complete uninstall and reinstall is required after removal of sharedUserId... and It "seems" that there is not much problem else than that.
But I cannot assure that it is really safe to delete this property and release an update on market.
This IssueTracker Thread created in June, 2019 is about this issue, but does not give detailed instruction on how to remove sharedUserId safely from an application.
Would deleting android:sharedUserId without any other modification end up with a critical problem?
If so, does anyone know an appropriate way to remove sharedUserId from Manifest file and safely release an update version?
OK, I just checked out the documentation again in original English version... and found out this sentence was omitted in Korean translation.
Note that existing apps cannot remove this value, as migrating off a
shared user ID is not supported.
So sharedUserId drives out problems in Android 10 (obviously in my case), and there is no way to remove it. Did I get it right?
If so... well... I find this very surprising... and disappointing...
This wasn't possible, but Android introduced a solution for this in sdk 33. It's called the android:sharedUserMaxSdkVersion attribute. It's only available in android 13. The documentation says:
The maximum device SDK version for which the application will remain in the user ID defined in sharedUserId. Used when the application wants to migrate out of using shared user ID, but has to maintain backwards compatibility with the API level specified and before.
So I think you should define: android:sharedUserMaxSdkVersion="29". But I'm not completely sure yet how this option should be interpreted.

Explain targetSdkLevel and how I should determine its correct value

Can you explain to me how I should determine the correct value for targetSdkLevel?
Let's say I want to build an app that works on all the versions from android 2.3.7 to 4.0.3, how should I set minSdkLevel and targetSdkLevel?
The former should match the API level of android 2.3.7 and the latter should match the API level of 4.0.3?
Then, when I develop my app, should I use only Methods/classes available in the oldest supported sdk level?
When I compile the app does it compile for 2.3.7 or 4.0.3?
I can not understand the purpose of targetSdkLevel, since the apk can not be compiled for the newer version specified in this tag, otherwise it could not work on versions down to the one specified by minSdkLevel... Why should I not set targetSdkLevel to the latest available level?
I've read also the official info about uses-sdk Manifest tag, but I still do not understand.. Can you help me clarifying this topic?
EDIT: thanks to all of you and excuse me for the duplicate question. I've read this Blog post and it really helped me. Great answers from all of you.
You should only use methods/classes available in the SDK specified by minSdkLevel, or otherwise wrap them with a proper check for the runtime API version.
Your application will be compiled with the SDK specified in the project itself, not by the one specified by either minSdkLevel nor targetSdkLevel.
You should set targetSdkLevel to the highest level API that you have tested the application with. This is because compatilibity behavior will be enabled/disabled for your application based on this value.
It clearly is explained here: http://developer.android.com/guide/topics/manifest/uses-sdk-element.html
minSdkVersion:
An integer designating the minimum API Level required for the
application to run. The Android system will prevent the user from
installing the application if the system's API Level is lower than the
value specified in this attribute. You should always declare this
attribute.
And for targetSdkVersion
An integer designating the API Level that the application targets. If
not set, the default value equals that given to minSdkVersion. This
attribute informs the system that you have tested against the target
version and the system should not enable any compatibility behaviors
to maintain your app's forward-compatibility with the target version.
The application is still able to run on older versions (down to
minSdkVersion).
What is that you don't understand here?
This is how you would set it:
<uses-sdk android:minSdkVersion="10"
android:targetSdkVersion="15"/>
You can read about the changes here, for API Level 14: http://developer.android.com/sdk/api_diff/14/changes.html
and here for API Level 4: http://developer.android.com/sdk/api_diff/4/changes.html
Build using the target, and then you can check and gracefully downgrade if the user is below the target. For example, if you are creating a location aware app, you might want to use PASSIVE_PROVIDER which is available starting with version 8. You could set the min version lower than 8 and check the android version. From there you could decide to use or not use PASSIVE_PROVIDER based on the version.
google suggests that you always use the latest version of the targetSdk , and also gives the lint tool to check for you that your classes and methods aren't too new for the minSdkVersion .
in case of a warning , you will need to think of how to handle it.
do note that as people has mentioned here , setting the targetSdk also means that it will change some aspects of the app .
one aspect is how the app treats the menu button : if you set the targetSdk to 11 or above , it means that you can't assume that there is a menu button , so you will have to deal with the action bar and put the options there in some way (or any other way, depending on your app design) .
if you set it to 10 or below , android will add this button (shown as 3 dots) on the screen for devices that don't have the menu button , like the htc one x or the galaxy nexus . do note that for some devices it looks ugly (takes a whole row for the htc one x , for example) .
so , in short , i would suggest setting the minSdk to the minimum that you can , in order to support as many people as possible , and the targetSdk to the maximum that you can , in order to enjoy all of the benefits that it can give you .

How does build target effects an android application? [duplicate]

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 Target versions are the same!
The comment posted by the OP to the question (basically stating that the targetSDK doesn't affect the compiling of an app) is entirely wrong! Sorry to be blunt.
In short, here is the purpose to declaring a different targetSDK from the minSDK: It means you are using features from a higher level SDK than your minimum, but you have ensured backwards compatibility. In other words, imagine that you want to use a feature that was only recently introduced, but that isn't critical to your application. You would then set the targetSDK to the version where this new feature was introduced and the minimum to something lower so that everyone could still use your app.
To give an example, let's say you're writing an app that makes extensive use of gesture detection. However, every command that can be recognised by a gesture can also be done by a button or from the menu. In this case, gestures are a 'cool extra' but aren't required. Therefore you would set the target sdk to 7 ("Eclair" when the GestureDetection library was introduced), and the minimumSDK to level 3 ("Cupcake") so that even people with really old phones could use your app. All you'd have to do is make sure that your app checked the version of Android it was running on before trying to use the gesture library, to avoid trying to use it if it didn't exist. (Admittedly this is a dated example since hardly anyone still has a v1.5 phone, but there was a time when maintaining compatibility with v1.5 was really important.)
To give another example, you could use this if you wanted to use a feature from Gingerbread or Honeycomb. Some people will get the updates soon, but many others, particularly with older hardware, might stay stuck with Eclair until they buy a new device. This would let you use some of the cool new features, but without excluding part of your possible market.
There is a really good article from the Android developer's blog about how to use this feature, and in particular, how to design the "check the feature exists before using it" code I mentioned above.
To the OP: I've written this mainly for the benefit of anyone who happens to stumble upon this question in the future, as I realise your question was asked a long time ago.
android:minSdkVersion
An integer designating the minimum API Level required for the application to run. The Android system will prevent the user from installing the application if the system's API Level is lower than the value specified in this attribute. You should always declare this attribute.
android:targetSdkVersion
An integer designating the API Level that the application is targetting.
With this attribute set, the application says that it is able to run on older versions (down to minSdkVersion), but was explicitly tested to work with the version specified here. Specifying this target version allows the platform to disable compatibility settings that are not required for the target version (which may otherwise be turned on in order to maintain forward-compatibility) or enable newer features that are not available to older applications. This does not mean that you can program different features for different versions of the platform—it simply informs the platform that you have tested against the target version and the platform should not perform any extra work to maintain forward-compatibility with the target version.
For more information refer this URL:
http://developer.android.com/guide/topics/manifest/uses-sdk-element.html
When you set targetSdkVersion="xx", you are certifying that your app works properly (e.g., has been thoroughly and successfully tested) at API level xx.
A version of Android running at an API level above xx will apply compatibility code automatically to support any features you might be relying upon that were available at or prior to API level xx, but which are now obsolete at that Android version's higher level.
Conversely, if you are using any features that became obsolete at or prior to level xx, compatibility code will not be automatically applied by OS versions at higher API levels (that no longer include those features) to support those uses. In that situation, your own code must have special case clauses that test the API level and, if the OS level detected is a higher one that no longer has the given API feature, your code must use alternate features that are available at the running OS's API level.
If it fails to do this, then some interface features may simply not appear that would normally trigger events within your code, and you may be missing a critical interface feature that the user needs to trigger those events and to access their functionality (as in the example below).
As stated in other answers, you might set targetSdkVersion higher than minSdkVersion if you wanted to use some API features initially defined at higher API levels than your minSdkVersion, and had taken steps to ensure that your code could detect and handle the absence of those features at lower levels than targetSdkVersion.
In order to warn developers to specifically test for the minimum API level required to use a feature, the compiler will issue an error (not just a warning) if code contains a call to any method that was defined at a later API level than minSdkVersion, even if targetSdkVersion is greater than or equal to the API level at which that method was first made available. To remove this error, the compiler directive
#TargetApi(nn)
tells the compiler that the code within the scope of that directive (which will precede either a method or a class) has been written to test for an API level of at least nn prior to calling any method that depends upon having at least that API level. For example, the following code defines a method that can be called from code within an app that has a minSdkVersion of less than 11 and a targetSdkVersion of 11 or higher:
#TargetApi(11)
public void refreshActionBarIfApi11OrHigher() {
//If the API is 11 or higher, set up the actionBar and display it
if(Build.VERSION.SDK_INT >= 11) {
//ActionBar only exists at API level 11 or higher
ActionBar actionBar = getActionBar();
//This should cause onPrepareOptionsMenu() to be called.
// In versions of the API prior to 11, this only occurred when the user pressed
// the dedicated menu button, but at level 11 and above, the action bar is
// typically displayed continuously and so you will need to call this
// each time the options on your menu change.
invalidateOptionsMenu();
//Show the bar
actionBar.show();
}
}
You might also want to declare a higher targetSdkVersion if you had tested at that higher level and everything worked, even if you were not using any features from an API level higher than your minSdkVersion. This would be just to avoid the overhead of accessing compatibility code intended to adapt from the target level down to the min level, since you would have confirmed (through testing) that no such adaptation was required.
An example of a UI feature that depends upon the declared targetSdkVersion would be the three-vertical-dot menu button that appears on the status bar of apps having a targetSdkVersion less than 11, when those apps are running under API 11 and higher. If your app has a targetSdkVersion of 10 or below, it is assumed that your app's interface depends upon the existence of a dedicated menu button, and so the three-dot button appears to take the place of the earlier dedicated hardware and/or onscreen versions of that button (e.g., as seen in Gingerbread) when the OS has a higher API level for which a dedicated menu button on the device is no longer assumed. However, if you set your app's targetSdkVersion to 11 or higher, it is assumed that you have taken advantage of features introduced at that level that replace the dedicated menu button (e.g., the Action Bar), or that you have otherwise circumvented the need to have a system menu button; consequently, the three-vertical-dot menu "compatibility button" disappears. In that case, if the user can't find a menu button, she can't press it, and that, in turn, means that your activity's onCreateOptionsMenu(menu) override might never get invoked, which, again in turn, means that a significant part of your app's functionality could be deprived of its user interface. Unless, of course, you have implemented the Action Bar or some other alternative means for the user to access these features.
minSdkVersion, by contrast, states a requirement that a device's OS version have at least that API level in order to run your app. This affects which devices are able to see and download your app when it is on the Google Play app store (and possibly other app stores, as well). It's a way of stating that your app relies upon OS (API or other) features that were established at that level, and does not have an acceptable way to deal with the absence of those features.
An example of using minSdkVersion to ensure the presence of a feature that is not API-related would be to set minSdkVersion to 8 in order to ensure that your app will run only on a JIT-enabled version of the Dalvik interpreter (since JIT was introduced to the Android interpreter at API level 8). Since performance for a JIT-enabled interpreter can be as much as five times that of one lacking that feature, if your app makes heavy use of the processor then you might want to require API level 8 or above in order to ensure adequate performance.
A concept can be better delivered with examples, always. I had trouble in comprehending these concept until I dig into Android framework source code, and do some experiments, even after reading all documents in Android developer sites & related stackoverflow threads. I'm gonna share two examples that helped me a lot to fully understand these concepts.
A DatePickerDialog will look different based on level that you put in AndroidManifest.xml file's targetSDKversion(<uses-sdk android:targetSdkVersion="INTEGER_VALUE"/>). If you set the value 10 or lower, your DatePickerDialog will look like left. On the other hand, if you set the value 11 or higher, a DatePickerDialog will look like right, with the very same code.
The code that I used to create this sample is super-simple. MainActivity.java looks :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickButton(View v) {
DatePickerDialog d = new DatePickerDialog(this, null, 2014, 5, 4);
d.show();
}
}
And activity_main.xml looks :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickButton"
android:text="Button" />
</RelativeLayout>
That's it. That's really every code that I need to test this.
And this change in look is crystal clear when you see the Android framework source code. It goes like :
public DatePickerDialog(Context context,
OnDateSetListener callBack,
int year,
int monthOfYear,
int dayOfMonth,
boolean yearOptional) {
this(context, context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB
? com.android.internal.R.style.Theme_Holo_Light_Dialog_Alert
: com.android.internal.R.style.Theme_Dialog_Alert,
callBack, year, monthOfYear, dayOfMonth, yearOptional);
}
As you can see, the framework gets current targetSDKversion and set different theme. This kind of code snippet(getApplicationInfo().targetSdkVersion >= SOME_VERSION) can be found here and there in Android framework.
Another example is about WebView class. Webview class's public methods should be called on main thread, and if not, runtime system throws a RuntimeException, when you set targetSDKversion 18 or higher. This behavior can be clearly delivered with its source code. It's just written like that.
sEnforceThreadChecking = context.getApplicationInfo().targetSdkVersion >=
Build.VERSION_CODES.JELLY_BEAN_MR2;
if (sEnforceThreadChecking) {
throw new RuntimeException(throwable);
}
The Android doc says, "As Android evolves with each new version, some behaviors and even appearances might change." So, we've looked behavior and appearance change, and how that change is accomplished.
In summary, the Android doc says "This attribute(targetSdkVersion) informs the system that you have tested against the target version and the system should not enable any compatibility behaviors to maintain your app's forward-compatibility with the target version.". This is really clear with WebView case. It was OK until JELLY_BEAN_MR2 released to call WebView class's public method on not-main thread. It is nonsense if Android framework throws a RuntimeException on JELLY_BEAN_MR2 devices. It just should not enable newly introduced behaviors for its interest, which cause fatal result. So, what we have to do is to check whether everything is OK on certain targetSDKversions. We get benefit like appearance enhancement with setting higher targetSDKversion, but it comes with responsibility.
EDIT :
disclaimer. The DatePickerDialog constructor that set different themes based on current targetSDKversion(that I showed above) actually has been changed in later commit. Nevertheless I used that example, because logic has not been changed, and those code snippet clearly shows targetSDKversion concept.
For those who want a summary,
android:minSdkVersion
is minimum version till your application supports. If your device has lower version of android , app will not install.
while,
android:targetSdkVersion
is the API level till which your app is designed to run. Means, your phone's system don't need to use any compatibility behaviours to maintain forward compatibility because you have tested against till this API.
Your app will still run on Android versions higher than given targetSdkVersion but android compatibility behaviour will kick in.
Freebie -
android:maxSdkVersion
if your device's API version is higher, app will not install. Ie. this is the max API till which you allow your app to install.
ie. for MinSDK -4, maxSDK - 8, targetSDK - 8 My app will work on minimum 1.6 but I also have used features that are supported only in 2.2 which will be visible if it is installed on a 2.2 device. Also, for maxSDK - 8, this app will not install on phones using API > 8.
At the time of writing this answer, Android documentation was not doing a great job at explaining it. Now it is very well explained. Check it here
If you get some compile errors for example:
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="15" />
.
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.
android:minSdkVersion and android:targetSdkVersion both are Integer value we need to declare in android manifest file but both are having different properties.
android:minSdkVersion: This is minimum required API level to run an android app. If we will install the same app on lower API version the parser error will be appear, and application not support problem will appear.
android:targetSdkVersion: Target sdk version is to set the Target API level of app. if this attribute not declared in manifest, minSdk version will be your TargetSdk Version. This is always true that "app support installation on all higher version of API we declared as TargetSdk Version". To make app limited target we need to declare maxSdkVersion in our manifest file...
If you are making apps that require dangerous permissions and set targetSDK to 23 or above you should be careful. If you do not check permissions on runtime you will get a SecurityException and if you are using code inside a try block, for example open camera, it can be hard to detect error if you do not check logcat.
Target sdk is the version you want to target, and min sdk is the minimum one.

Android compatibilty settings in AndroidManifest.xml

I have an app to release which works on all android screen-sizes (except smaller) and densities above SDK version 2.0.
It will also run on extra large screens.
Currently I have added this:
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="false"
android:anyDensity="true"
/>
But I also need to add android:xlargeScreens="true" , to allow it visible in android market on extra large screen devices, since by default it is false.
But to add android:xlargeScreens I need to change my eclipse targetsettings to 2.3 as this attribute was added from API level 9.
So what should I do with my target compilation settings for this scenario ? Should it be 2.3 while compiling ? If yes, then will the app not give any problems while running on devices with 2.0 version ?
Yes you need to change the uses sdk to 2.3 but make sure that you are not using any newer apis which are not in 2.0 or whatever your minimum supported sdk version is. Or in case you want to use them you have to use reflection.
But more about how to use the sdk versions is here and more about uses-sdk is here.
I do the same in my application and make sure you test your application in both[all] the versions before you release.
Best,
Achie.
I'm moving this from the comments to make it more clear for others looking at this question in the future.
When supporting both old and new versions of Android it can be confusing how applications manage to run despite many things change with in the frameworks during each new release, I'm going to try and clarify this here.
An application written for the 1.5 sdk can only call functions that exist for that API level, so for instance the multi touch api's didn't exist in 1.5 and never will. Now you say "Ok but I don't need to call any newer APIs, I just want my app to work in 2.3 and have a2sd support" And I say "Ok, just change your targetApi in the manifest, set the minSDK and compile against 2.3 and you're good to go."
Now why does that work? What if the onMeasure() method for ListView was changed in 2.2 and now calls betterCalculateFunction() within onMeasure()? Why does my app still work?
This is the advantage of late binding in Java. You see, Java is never compiled until it reaches a device and is running, what you are doing in Eclipse is converting it to byte code which contains a bunch of byte code instructions that are later interpreted by the device. The byte code will NEVER contain a reference to betterCalculateFunction() though (unless you directly call it. Calling onMeasure() is indirect). This can happen because when your code is running on the device it gets linked against the Android framework on the device and your code calls onMeasure() directly because it is a public outward facing API. The path of execution will then enter the framework and call whatever it needs to, then once its done return to your code.
So on 1.5 you might see
doStuff (your code) -> onMeasure
(public API) -> done
and 2.2
doStuff (your code) -> onMeasure
(public API) ->
betterCalculateFunction (private
function) ->done
Now if you need to call functions that may or may not exist depending on API level then I suggest you look at a related answer of mine here stackoverflow: gracefully downgrade your app
Hope that clears some things up.
I haven't tried 2.3, but that's what I do with 2.2.
I compile for 2.2 and test on 1.6 to make sure everything works how I'm expecting. I haven't run in to any issues with it.
To double check, set your target for 2.3 and then setup an emulator for a lower rev version to make sure it all works.
The default value for android:xlargeScreens is true, so you don't have to change anything - it's on by default, as long as your minSdkVersion or targetSdkVersion is higher than 4.
http://developer.android.com/guide/topics/manifest/supports-screens-element.html
Here is an official Android developer blog explanation of how this works:
http://android-developers.blogspot.com/2010/07/how-to-have-your-cupcake-and-eat-it-too.html
In summary: you can use the newest XML whilst still supporting the older OS versions in a back compatible way.
While reading this blog post I guess I have an answer on my old question. An extract below (which is for another manifest attribute "requiresSmallestWidthDp" introduced from 3.2):
"The catch is that you must compile your application against Android 3.2 or higher in order to use the requiresSmallestWidthDp attribute. Older versions don’t understand this attribute and will raise a compile-time error. The safest thing to do is develop your app against the platform that matches the API level you’ve set for minSdkVersion. When you’re making final preparations to build your release candidate, change the build target to Android 3.2 and add the requiresSmallestWidthDp attribute. Android versions older than 3.2 simply ignore that XML attribute, so there’s no risk of a runtime failure."
For different screens you have to create multiple apk then it reduces size of your application.In each application's manifest you have to define according to following link.
http://developer.android.com/guide/practices/screens-distribution.html

Android Min SDK Version vs. Target SDK Version

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 Target versions are the same!
The comment posted by the OP to the question (basically stating that the targetSDK doesn't affect the compiling of an app) is entirely wrong! Sorry to be blunt.
In short, here is the purpose to declaring a different targetSDK from the minSDK: It means you are using features from a higher level SDK than your minimum, but you have ensured backwards compatibility. In other words, imagine that you want to use a feature that was only recently introduced, but that isn't critical to your application. You would then set the targetSDK to the version where this new feature was introduced and the minimum to something lower so that everyone could still use your app.
To give an example, let's say you're writing an app that makes extensive use of gesture detection. However, every command that can be recognised by a gesture can also be done by a button or from the menu. In this case, gestures are a 'cool extra' but aren't required. Therefore you would set the target sdk to 7 ("Eclair" when the GestureDetection library was introduced), and the minimumSDK to level 3 ("Cupcake") so that even people with really old phones could use your app. All you'd have to do is make sure that your app checked the version of Android it was running on before trying to use the gesture library, to avoid trying to use it if it didn't exist. (Admittedly this is a dated example since hardly anyone still has a v1.5 phone, but there was a time when maintaining compatibility with v1.5 was really important.)
To give another example, you could use this if you wanted to use a feature from Gingerbread or Honeycomb. Some people will get the updates soon, but many others, particularly with older hardware, might stay stuck with Eclair until they buy a new device. This would let you use some of the cool new features, but without excluding part of your possible market.
There is a really good article from the Android developer's blog about how to use this feature, and in particular, how to design the "check the feature exists before using it" code I mentioned above.
To the OP: I've written this mainly for the benefit of anyone who happens to stumble upon this question in the future, as I realise your question was asked a long time ago.
android:minSdkVersion
An integer designating the minimum API Level required for the application to run. The Android system will prevent the user from installing the application if the system's API Level is lower than the value specified in this attribute. You should always declare this attribute.
android:targetSdkVersion
An integer designating the API Level that the application is targetting.
With this attribute set, the application says that it is able to run on older versions (down to minSdkVersion), but was explicitly tested to work with the version specified here. Specifying this target version allows the platform to disable compatibility settings that are not required for the target version (which may otherwise be turned on in order to maintain forward-compatibility) or enable newer features that are not available to older applications. This does not mean that you can program different features for different versions of the platform—it simply informs the platform that you have tested against the target version and the platform should not perform any extra work to maintain forward-compatibility with the target version.
For more information refer this URL:
http://developer.android.com/guide/topics/manifest/uses-sdk-element.html
When you set targetSdkVersion="xx", you are certifying that your app works properly (e.g., has been thoroughly and successfully tested) at API level xx.
A version of Android running at an API level above xx will apply compatibility code automatically to support any features you might be relying upon that were available at or prior to API level xx, but which are now obsolete at that Android version's higher level.
Conversely, if you are using any features that became obsolete at or prior to level xx, compatibility code will not be automatically applied by OS versions at higher API levels (that no longer include those features) to support those uses. In that situation, your own code must have special case clauses that test the API level and, if the OS level detected is a higher one that no longer has the given API feature, your code must use alternate features that are available at the running OS's API level.
If it fails to do this, then some interface features may simply not appear that would normally trigger events within your code, and you may be missing a critical interface feature that the user needs to trigger those events and to access their functionality (as in the example below).
As stated in other answers, you might set targetSdkVersion higher than minSdkVersion if you wanted to use some API features initially defined at higher API levels than your minSdkVersion, and had taken steps to ensure that your code could detect and handle the absence of those features at lower levels than targetSdkVersion.
In order to warn developers to specifically test for the minimum API level required to use a feature, the compiler will issue an error (not just a warning) if code contains a call to any method that was defined at a later API level than minSdkVersion, even if targetSdkVersion is greater than or equal to the API level at which that method was first made available. To remove this error, the compiler directive
#TargetApi(nn)
tells the compiler that the code within the scope of that directive (which will precede either a method or a class) has been written to test for an API level of at least nn prior to calling any method that depends upon having at least that API level. For example, the following code defines a method that can be called from code within an app that has a minSdkVersion of less than 11 and a targetSdkVersion of 11 or higher:
#TargetApi(11)
public void refreshActionBarIfApi11OrHigher() {
//If the API is 11 or higher, set up the actionBar and display it
if(Build.VERSION.SDK_INT >= 11) {
//ActionBar only exists at API level 11 or higher
ActionBar actionBar = getActionBar();
//This should cause onPrepareOptionsMenu() to be called.
// In versions of the API prior to 11, this only occurred when the user pressed
// the dedicated menu button, but at level 11 and above, the action bar is
// typically displayed continuously and so you will need to call this
// each time the options on your menu change.
invalidateOptionsMenu();
//Show the bar
actionBar.show();
}
}
You might also want to declare a higher targetSdkVersion if you had tested at that higher level and everything worked, even if you were not using any features from an API level higher than your minSdkVersion. This would be just to avoid the overhead of accessing compatibility code intended to adapt from the target level down to the min level, since you would have confirmed (through testing) that no such adaptation was required.
An example of a UI feature that depends upon the declared targetSdkVersion would be the three-vertical-dot menu button that appears on the status bar of apps having a targetSdkVersion less than 11, when those apps are running under API 11 and higher. If your app has a targetSdkVersion of 10 or below, it is assumed that your app's interface depends upon the existence of a dedicated menu button, and so the three-dot button appears to take the place of the earlier dedicated hardware and/or onscreen versions of that button (e.g., as seen in Gingerbread) when the OS has a higher API level for which a dedicated menu button on the device is no longer assumed. However, if you set your app's targetSdkVersion to 11 or higher, it is assumed that you have taken advantage of features introduced at that level that replace the dedicated menu button (e.g., the Action Bar), or that you have otherwise circumvented the need to have a system menu button; consequently, the three-vertical-dot menu "compatibility button" disappears. In that case, if the user can't find a menu button, she can't press it, and that, in turn, means that your activity's onCreateOptionsMenu(menu) override might never get invoked, which, again in turn, means that a significant part of your app's functionality could be deprived of its user interface. Unless, of course, you have implemented the Action Bar or some other alternative means for the user to access these features.
minSdkVersion, by contrast, states a requirement that a device's OS version have at least that API level in order to run your app. This affects which devices are able to see and download your app when it is on the Google Play app store (and possibly other app stores, as well). It's a way of stating that your app relies upon OS (API or other) features that were established at that level, and does not have an acceptable way to deal with the absence of those features.
An example of using minSdkVersion to ensure the presence of a feature that is not API-related would be to set minSdkVersion to 8 in order to ensure that your app will run only on a JIT-enabled version of the Dalvik interpreter (since JIT was introduced to the Android interpreter at API level 8). Since performance for a JIT-enabled interpreter can be as much as five times that of one lacking that feature, if your app makes heavy use of the processor then you might want to require API level 8 or above in order to ensure adequate performance.
A concept can be better delivered with examples, always. I had trouble in comprehending these concept until I dig into Android framework source code, and do some experiments, even after reading all documents in Android developer sites & related stackoverflow threads. I'm gonna share two examples that helped me a lot to fully understand these concepts.
A DatePickerDialog will look different based on level that you put in AndroidManifest.xml file's targetSDKversion(<uses-sdk android:targetSdkVersion="INTEGER_VALUE"/>). If you set the value 10 or lower, your DatePickerDialog will look like left. On the other hand, if you set the value 11 or higher, a DatePickerDialog will look like right, with the very same code.
The code that I used to create this sample is super-simple. MainActivity.java looks :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickButton(View v) {
DatePickerDialog d = new DatePickerDialog(this, null, 2014, 5, 4);
d.show();
}
}
And activity_main.xml looks :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickButton"
android:text="Button" />
</RelativeLayout>
That's it. That's really every code that I need to test this.
And this change in look is crystal clear when you see the Android framework source code. It goes like :
public DatePickerDialog(Context context,
OnDateSetListener callBack,
int year,
int monthOfYear,
int dayOfMonth,
boolean yearOptional) {
this(context, context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB
? com.android.internal.R.style.Theme_Holo_Light_Dialog_Alert
: com.android.internal.R.style.Theme_Dialog_Alert,
callBack, year, monthOfYear, dayOfMonth, yearOptional);
}
As you can see, the framework gets current targetSDKversion and set different theme. This kind of code snippet(getApplicationInfo().targetSdkVersion >= SOME_VERSION) can be found here and there in Android framework.
Another example is about WebView class. Webview class's public methods should be called on main thread, and if not, runtime system throws a RuntimeException, when you set targetSDKversion 18 or higher. This behavior can be clearly delivered with its source code. It's just written like that.
sEnforceThreadChecking = context.getApplicationInfo().targetSdkVersion >=
Build.VERSION_CODES.JELLY_BEAN_MR2;
if (sEnforceThreadChecking) {
throw new RuntimeException(throwable);
}
The Android doc says, "As Android evolves with each new version, some behaviors and even appearances might change." So, we've looked behavior and appearance change, and how that change is accomplished.
In summary, the Android doc says "This attribute(targetSdkVersion) informs the system that you have tested against the target version and the system should not enable any compatibility behaviors to maintain your app's forward-compatibility with the target version.". This is really clear with WebView case. It was OK until JELLY_BEAN_MR2 released to call WebView class's public method on not-main thread. It is nonsense if Android framework throws a RuntimeException on JELLY_BEAN_MR2 devices. It just should not enable newly introduced behaviors for its interest, which cause fatal result. So, what we have to do is to check whether everything is OK on certain targetSDKversions. We get benefit like appearance enhancement with setting higher targetSDKversion, but it comes with responsibility.
EDIT :
disclaimer. The DatePickerDialog constructor that set different themes based on current targetSDKversion(that I showed above) actually has been changed in later commit. Nevertheless I used that example, because logic has not been changed, and those code snippet clearly shows targetSDKversion concept.
For those who want a summary,
android:minSdkVersion
is minimum version till your application supports. If your device has lower version of android , app will not install.
while,
android:targetSdkVersion
is the API level till which your app is designed to run. Means, your phone's system don't need to use any compatibility behaviours to maintain forward compatibility because you have tested against till this API.
Your app will still run on Android versions higher than given targetSdkVersion but android compatibility behaviour will kick in.
Freebie -
android:maxSdkVersion
if your device's API version is higher, app will not install. Ie. this is the max API till which you allow your app to install.
ie. for MinSDK -4, maxSDK - 8, targetSDK - 8 My app will work on minimum 1.6 but I also have used features that are supported only in 2.2 which will be visible if it is installed on a 2.2 device. Also, for maxSDK - 8, this app will not install on phones using API > 8.
At the time of writing this answer, Android documentation was not doing a great job at explaining it. Now it is very well explained. Check it here
If you get some compile errors for example:
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="15" />
.
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.
android:minSdkVersion and android:targetSdkVersion both are Integer value we need to declare in android manifest file but both are having different properties.
android:minSdkVersion: This is minimum required API level to run an android app. If we will install the same app on lower API version the parser error will be appear, and application not support problem will appear.
android:targetSdkVersion: Target sdk version is to set the Target API level of app. if this attribute not declared in manifest, minSdk version will be your TargetSdk Version. This is always true that "app support installation on all higher version of API we declared as TargetSdk Version". To make app limited target we need to declare maxSdkVersion in our manifest file...
If you are making apps that require dangerous permissions and set targetSDK to 23 or above you should be careful. If you do not check permissions on runtime you will get a SecurityException and if you are using code inside a try block, for example open camera, it can be hard to detect error if you do not check logcat.
Target sdk is the version you want to target, and min sdk is the minimum one.

Categories

Resources