From 5f0d53ba20338d5335b9560ef566c9066ef4df76 Mon Sep 17 00:00:00 2001 From: Jan Vidar Krey Date: Fri, 15 Sep 2017 16:24:11 +0200 Subject: [PATCH] Support bounding targetSdkVersion between minSdkVersion and maxSdkVersion It is possible to create a an AndroidStudio project that uses the following nonsense settings: defaultConfig { minSdkVersion 15 maxSdkVersion 19 targetSdkVersion 25 } The application is successfully built by Android Studio, and the APK works when installed on the relevant devices, however the app cannot be re-built with Apktool afterwards. This patch works around the problem by explicitly setting the targetSdkVersion to the max of the maxSdkVersion and min of the minSdkVersion only if these are specified. --- .../brut/androlib/res/AndrolibResources.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java b/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java index 0d0ef7fa..5b457620 100644 --- a/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java +++ b/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java @@ -307,6 +307,22 @@ final public class AndrolibResources { mSharedLibrary = flag; } + // Ensure that targetSdkVersion is between minSdkVersion/maxSdkVersion if + // they are specified. + private String checkTargetSdkVersionBounds() + { + int target = Integer.parseInt(mTargetSdkVersion); + int min = (mMinSdkVersion != null) ? Integer.parseInt(mMinSdkVersion) : 0; + int max = (mMaxSdkVersion != null) ? Integer.parseInt(mMaxSdkVersion) : target; + + // Your APK seems broken otherwise. + assert (min <= max); + + target = Math.min(max, target); + target = Math.max(min, target); + return Integer.toString(target); + } + public void aaptPackage(File apkFile, File manifest, File resDir, File rawDir, File assetDir, File[] include) throws AndrolibException { @@ -368,7 +384,7 @@ final public class AndrolibResources { } if (mTargetSdkVersion != null) { cmd.add("--target-sdk-version"); - cmd.add(mTargetSdkVersion); + cmd.add(checkTargetSdkVersionBounds()); } if (mMaxSdkVersion != null) { cmd.add("--max-sdk-version");