Android N - Cannot run on lower API though minSDK set to 14

mjosh picture mjosh · Mar 11, 2016 · Viewed 8.5k times · Source

I am trying to run the APK on API 22 device after updating compileSdkVersion to N but unable to do so.

compileSdkVersion 'android-N'
buildToolsVersion "24.0.0 rc1"

defaultConfig {
       minSdkVersion 14
       targetSdkVersion 'N'
}

enter image description here

Answer

CommonsWare picture CommonsWare · Mar 11, 2016

Out of the box, the build tools are set up to block you from running N Developer Preview apps on older devices. Presumably, this is a sloppy way for Google to try to prevent people from shipping stuff built off of the preview. This approach was also used in the past two developer previews. So, Google does not want you testing your N Developer Preview app on your Android 5.0 (API Level 22) device to see if you are handling backwards compatibility correctly.

¯\_(ツ)_/¯

Fortunately, you can hack in a solution:

android {
    compileSdkVersion 'android-N'
    buildToolsVersion "24.0.0 rc1"

    defaultConfig {
      minSdkVersion 15
      targetSdkVersion 'N'
    }

    // based on http://stackoverflow.com/a/27372806/115145

    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.processManifest.doLast {
                def manifestOutFile = output.processManifest.manifestOutputFile
                def xml = new XmlParser().parse(manifestOutFile)
                def usesSdk = xml.'uses-sdk'

                usesSdk.replaceNode{
                    'uses-sdk'('android:minSdkVersion': '15',
                               'android:targetSdkVersion': '15')
                }

                def fw=new FileWriter(manifestOutFile.toString())

                new XmlNodePrinter(new PrintWriter(fw)).print(xml)
            }
        }
    }
}

What the tools demand is targetSdkVersion 'N', and that's what breaks your ability to run the app on older devices. So, this hunk of Groovy code allows the build tools to start with targetSdkVersion 'N', then swaps in another targetSdkVersion value into the generated manifest, before packaging. In this case, I am setting the minSdkVersion and targetSdkVersion to 15, but you can substitute in your own values. Also, you will need to rebuild or clean your project for the change to take effect.

On the plus side, the resulting app can be installed and run on an older Android device (though possibly only through a command-line build; I think Android Studio didn't like this technique).

On the minus side, your targetSdkVersion will not actually be N, which may impact some behaviors on N Developer Preview devices. You might want to set up a particular build type that you use for the backwards-compatibility testing and only do my hack-the-manifest trick on that build type. Then, you can test both using an official N Developer Preview setup and perform some measure of backwards compatibility testing in one build.