zed
zed

Reputation: 3267

Android: Get TargetSDKVersion in runtime

Can I get the used TargetSDKVersion in runtime?

This is due to the fact that the WebView in Android API 19> handles pixels differently than pre 19.

This is for a library and so I would not like to have the developer enter it manually.

My comment: I am using my Nexus 5 API 21 Lollipop. Changing TargetSDKVersion changes the way javascript of the html reads the widths by a multiple of the screen density. I have just changed it to 14 then to 19, and I confirm this.

Upvotes: 16

Views: 18541

Answers (5)

Fedir Tsapana
Fedir Tsapana

Reputation: 1352

You can even set it in runtime:

        applicationInfo.targetSdkVersion = 32

This may work for example if some external api (WebView in my case) works differently depending of your app's target api and you need to restore previous behaviour on earlier platforms (in that case dont forget to wrap this with if (Build.VERSION.SDK_INT <= xxx)

Upvotes: 0

Kasim Rangwala
Kasim Rangwala

Reputation: 1835

In my case, I've done this

int targetSdkVersion = getApplicationContext().getApplicationInfo().targetSdkVersion;

Upvotes: 41

GoRoS
GoRoS

Reputation: 5375

Having the following config in an Android Marshmallow (API 23) phone:

defaultConfig {
      applicationId "com.mytestapp"
      minSdkVersion 9
      targetSdkVersion 22
      versionCode 1
      versionName "1.0.0"
}

Another direct approach to get the actual running app targetSdkVersion is:

Context mContext = getApplicationContext();
int targetSdkVersion = mContext.getApplicationInfo().targetSdkVersion; // Outputs 22
int mobileSdkVersion = Build.VERSION.SDK_INT; // Outputs 23

Upvotes: 4

Jorgesys
Jorgesys

Reputation: 126445

This is another way to get the targetSdkVersionof my application in runtime, using Android Studio:

try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            int targetSdkVersion = packageInfo.applicationInfo.targetSdkVersion;

        }
        catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }

the value of targetSDKVersion is defined into my build.gradle file

   defaultConfig {
        applicationId "com.tuna.hello.androidstudioapplication"
        minSdkVersion 9
        targetSdkVersion 22
        versionCode 12
        versionName "1.0"
    }

Upvotes: 7

Kirill Shalnov
Kirill Shalnov

Reputation: 2216

About target SDK version, look to the ApplicationInfo class (get it from here)

int version = 0;
IPackageManager pm = AppGlobals.getPackageManager();
try {
    ApplicationInfo applicationInfo = pm.getApplicationInfo(yourAppName, 0);
    if (applicationInfo != null) {
      version = applicationInfo.targetSdkVersion;
    }
}

OR

If we talk about device OS version

Build class contain information about version

android.os.Build.VERSION.SDK_INT

Upvotes: 9

Related Questions