alwaystest / Blog

24 stars 2 forks source link

Android应用打包ApplicationId #43

Open alwaystest opened 7 years ago

alwaystest commented 7 years ago

Android应用打包ApplicationId

标签(空格分隔): Android


打包Android应用的时候可以定义打包以后的应用的包名,使之与编写代码时Manifest中定义的Package不同。

With the new Android Gradle build system, you can easily build multiple different versions of your app; for example, you can build both a "free" version and a "pro" version of your app (using flavors), and these should have different packages in the Google Play store such that they can be installed and purchased separately, both installed at the same time, and so on. Similarly, you may also build both "debug" and "alpha" and "beta" versions of your app (using build types) and these can also similarly contribute to unique package names. http://tools.android.com/tech-docs/new-build-system/applicationid-vs-packagename

按照官方的说明,可以通过修改ApplicationId的方式 达到生成不同包名的应用的效果。

APK的包名相当于其身份证号,用于辨识App是否可以同时存在与一个设备上。

于是我修改Build.gradle为以下方式

/** AndroidManifest */
<manifest ... package="com.eric.test">

/** build.gradle */
android{
    defaultConfig{
        applicationId "cn.android.lalala"
    }
}

结果打包以后安装的应用报错,提示找不到类。

使用Android Studio分析APK发现默认的class.dex中没有工程中的Class。解开包之后发现还有一个class2.dex。class.dex文件很小,明显代码没有写入到这里,而是在class2.dex。 (在另一台电脑上重复同样的过程,发现并没有这个问题,尴尬)


修改defaultConfig中的applicationId,不够灵活,如果要生成另一个包名,则需要再次修改。

这种情况下,需要使用Product Flavors来进行配置,详细解释在https://developer.android.com/studio/build/build-variants.html#product-flavors

使用Product Flavors之后,Build.gradle是这样的

/** AndroidManifest */
<manifest ... package="com.eric.test">

/** build.gradle */
android{
    defaultConfig{
        applicationId "com.eric.test"
    }

    productFlavors{
        lalala{
            applicationId "lala.lala.la"
        }
    }
}

注意,修改过包名之后一些第三方的服务可能由于签名key与包名做了绑定,需要验证各种使用Key的第三方服务是否正常。

我本来以为defaultConfig的applicationId是不能修改的,由于上面的问题在别的电脑上没有重现,所以应该是BUG。