java - 可以将包名称变量传递到 Android 源代码中吗?

标签 java android android-studio

这通常是构建 Android 代码以声明包和导入的方式:

package com.company.myApp

import com.company.myApp.SomeClass
import com.company.myApp.somePackage.SomeOtherClass

是否有任何方法可以使用 Android Studio/Java/任何方式传递“编译时”变量或 pragma 以有效地将“com.company.myApp”字符串传递给源代码?像这样的东西:

package BASE_PACKAGE_NAME

import BASE_PACKAGE_NAME.SomeClass
import BASE_PACKAGE_NAME.somePackage.SomeOtherClass 

最佳答案

我个人不知道有什么适合你的 但正如我在 http://tools.android.com/tech-docs/new-build-system/applicationid-vs-packagename 中读到的那样

The final package that is used in your built .apk's manifest, and is the package your app is known as on your device and in the Google Play store, is the "application id".

The package that is used in your source code to refer to your R class, and to resolve any relative activity/service registrations, continues to be called the "package".

您可以在您的 gradle 文件中指定应用程序 ID,如下所示:

应用程序/build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 19
    buildToolsVersion "19.1"

    defaultConfig {
        applicationId "com.example.my.app"
        minSdkVersion 15
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }

Here comes the critical part: When you've done the above, the two packages are independent. You are completely free to refactor your code - changing the internal package used for your activities and services, updating your Manifest package, and refactoring your import statements. This will have no bearing on the final id of your application, which is now always going to be the applicationId specified in the Gradle file.

You can vary the applicationId of your app for flavors and build types by using the following Gradle DSL methods:

应用程序/build.gradle:

productFlavors {
    pro {
        applicationId = "com.example.my.pkg.pro"
    }
    free {
        applicationId = "com.example.my.pkg.free"
    }
}

buildTypes {
    debug {
        applicationIdSuffix ".debug"
    }
}
....

关于java - 可以将包名称变量传递到 Android 源代码中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39951303/

相关文章:

java - euler 项目 #10 无法在 java 上得到答案

java - 插入 AssignmentOperator ArrayInitializer 错误

安卓定时器泄露

android - 开发建议 : Phonegap or Eclipse for Android

java - 如何选择Android Studio的Java版本

java - 如何将 CSV 文件中的数据输入到我的代码中?

java - Android:基于屏幕尺寸的方向变化

android - getStreamVolume提供空指针异常

android-studio - 为什么在打开 flutter 项目时 Android Studio 中缺少 LogCat 和 AVD Manager

Android工作室布局xml不更新