pbm
pbm

Reputation: 5371

Can a package name variable be passed into Android source code?

This is normally how one structures Android code for declaring the package and importing:

package com.company.myApp

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

Is there any way of using Android Studio/Java/whatever to pass a "compile-time" variable or pragma to effectively pass in the "com.company.myApp" string to the source code? Something like:

package BASE_PACKAGE_NAME

import BASE_PACKAGE_NAME.SomeClass
import BASE_PACKAGE_NAME.somePackage.SomeOtherClass 

Upvotes: 1

Views: 1200

Answers (1)

zombie
zombie

Reputation: 5269

i personally don't know anything that would do the job for you but as i read in 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".

You can specify the application id in your gradle file as follows:

app/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:

app/build.gradle:

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

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

Upvotes: 2

Related Questions