Ulrich Scheller
Ulrich Scheller

Reputation: 11910

Android – multiple custom versions of the same app

Whats the best way to deploy several customized versions of a Android application?

Currently I have a script to exchange the resource folder for getting a customized version of my app. It works great, but all custom versions still have the same package name in the AndroidManifest.xml. Therefore it is not possible to install two customized versions of the app at the same time.

This is one solution for this problem, but that has to be done by hand

Can you think of a more easy solution, or how this could be built into a skript?

(btw: it is not for a porn/spam/whatever app, not even a paid one)

Upvotes: 48

Views: 29676

Answers (8)

craned
craned

Reputation: 3051

You definitely want to use Gradle flavors that comes natively, encouraged even, on Android Studio.

It seems to explain all the basics really well. I just finished converting to Gradle today, and it works great. Custom app icons, names, and strings, etc.

As the website explains, part of the purpose behind this design was to make it more dynamic and more easily allow multiple APKs to be created with essentially the same code, which sounds similar what you're doing.

I probably didn't explain it the best, but that website does a pretty good job.

Upvotes: 6

M. Usman Khan
M. Usman Khan

Reputation: 4408

I think the best way is to create a new project and copy the stuff. steps, - create new android project without a class - create package (package name should be corresponding to the one in the manifest file), or just copy the package name in the 'gen' folder - copy the java files - copy the drawable folders - copy the layout files - copy any other file(s) used in ur project - copy manifest file's data

this has been simpler for me for the task

Upvotes: 0

18446744073709551615
18446744073709551615

Reputation: 16832

I wound up with a script that patches the sources; patching the source sounds risky, but in presence of version control the risk is acceptable.

So I made one version, committed the source, made the other version, committed the source, and looking at diffs wrote a patching script in Python.

I am not sure if it is the best solution. (And the code misses some os.path.joins)

The heart of the script is the following function:

# In the file 'fname',
# find the text matching "before oldtext after" (all occurrences) and
# replace 'oldtext' with 'newtext' (all occurrences).
# If 'mandatory' is true, raise an exception if no replacements were made.
def fileReplace(fname,before,newtext,after,mandatory=True):
    with open(fname, 'r+') as f:
    read_data = f.read()
    pattern = r"("+re.escape(before)+r")\w+("+re.escape(after)+r")"
    replacement = r"\1"+newtext+r"\2"
    new_data,replacements_made = re.subn(pattern,replacement,read_data,flags=re.MULTILINE)
    if replacements_made and really:
        f.seek(0)
        f.truncate()
        f.write(new_data)
        if verbose:
            print "patching ",fname," (",replacements_made," occurrence", "s" if 1!=replacements_made else "",")"
    elif replacements_made:
        print fname,":"
        print new_data
    elif mandatory:
        raise Exception("cannot patch the file: "+fname)

And you may find the following one of use:

# Change the application resource package name everywhere in the src/ tree.
# Yes, this changes the java files. We hope that if something goes wrong,
# the version control will save us.
def patchResourcePackageNameInSrc(pname):
    for root, dirs, files in os.walk('src'):
    if '.svn' in dirs:
        dirs.remove('.svn')
    for fname in files:
        fileReplace(os.path.join(root,fname),"import com.xyz.",pname,".R;",mandatory=False)

There is also a function that copies assets from x-assets-cfgname to assets (earlier it turned out that for me it is more convenient to have a subdirectory in assets).

def copyAssets(vname,force=False):
    assets_source = "x-assets-"+vname+"/xxx"
    assets_target = "assets/xxx"
    if not os.path.exists(assets_source):
        raise Exception("Invalid variant name: "+vname+" (the assets directory "+assets_source+" does not exist)")
    if os.path.exists(assets_target+"/.svn"):
        raise Exception("The assets directory must not be under version control! "+assets_target+"/.svn exists!")
    if os.path.exists(assets_target):
        shutil.rmtree(assets_target)
    shutil.copytree(assets_source, assets_target, ignore=shutil.ignore_patterns('.svn'))

Well, you get the idea. Now you can write your own script.

Upvotes: 0

larham1
larham1

Reputation: 12216

Perhaps the built-in Android "library" concept was not fully baked at the time of the original post, but it may be the preferred method as of 2011. Follow these steps for an ant build:

Starting from a working app (let's call it directory "myOrigApp", package com.foo.myapp), just add this line to "default.properties" to make it a library:

android.library=true

Now create a new app in a sibling directory in any way you prefer (let's call it directory "sibling", package com.foo.myVariant). Using Intellij Idea, for example, create a project 'from scratch' with directory 'sibling' and it will create all the files/directories you would normally need.

In that new, sibling directory edit "default.properties" to add the dependency:

android.library.reference.1=../myOrigApp

Copy over the Manifest from the original dir:

cd sibling
cp ../myOrigApp/AndroidManifest.xml  ../myOrigApp/local.properties ../myOrigApp/build.properties  .

Edit that copied Manifest file to change its package name to your new variant, "com.foo.myVarient"; that's the only change.

If you just run the ant build scripts, you may be done. (I had to just set up signing keys.)

If you want to set up an IDE like Idea to have the library project as a dependent of the variant project, follow these steps to add a library project to the variant project (assumes you already have a project set up for both):

  • Open the original project, bring up Project Settings, select your Facet and check "Is Library Project" and save.
  • Open the variant project, bring up Project Settings, select Modules
  • Add a module
  • Select “Import existing module”
  • Browse to the Original directory (myOrigApp) and select its .iml file (IntelliJ project source file)
  • Click "Finish." (The library project is added as a module within the variant project.)
  • In the modules list click over the Variant project to select it.
  • On the right hand side select the "Dependencies" tab.
  • Click "Add…"
  • Choose "Module dependency…" (A list should appear that includes the name of the module/library you previously added to the project--perhaps the only entry in the list).
  • Select the library project you added and press OK. (It will be added to the list of dependencies of your project.)
  • Press OK to finish configuring the project. (You should see 2 modules, with the library's resources and classes available and recognized in the Variant project.)

Upvotes: 24

figofuture
figofuture

Reputation: 251

Support Multiple Partners Prepare config.xml

Build project for different partner

<!--partner.dir, pkg.name, ver.code, ver.name are input from command line when execute 'ant' -->

<!-- set global properties for this build -->
<property name="build.bin" location="bin"/>
<property name="build.gen" location="gen"/>
<property name="src" location="src"/>
<property name="res" location="res"/>

<target name="preparefiles" description="Prepare files for different partner" >
    <delete dir="${build.bin}" />
    <delete dir="${build.gen}" />

    <copy todir="${res}" overwrite="true" />
        <fileset dir="${partner.dir}/res" /> 
    </copy>

    <!-- change the import in all Java source files -->
    <replaceregexp file="AndroidManifest.xml"
        match='android.versionCode="(.*)"'
        replace='android.versionCode="${ver.code}"'
        byline="false">

    <replaceregexp file="AndroidManifest.xml"
        match='android.versionName="(.*)"'
        replace='android.versionName="${ver.name}"'
        byline="false">

    <replaceregexp file="AndroidManifest.xml"
        match='package="(.*)"'
        replace='package="${pkg.name}"'
        byline="false">

    <!-- change the package name in AndroidManifest -->
    <replaceregexp flags="g" byline="false">
        <regexp pattern="import(.*)com.myproject.com.R;" /> 
        <substitution expression="import com.${pkg.name}.R;" />
        <fileset dir="${src}" includes="**/*.java" /> 
    </replaceregexp>

    <replaceregexp flags="g" byline="false">
        <regexp pattern="(package com.myproject.com;)" /> 
        <substitution expression="\1&#10;import com.${pkg.name}.R;" />
        <fileset dir="${src}" includes="**/*.java" /> 
    </replaceregexp>
</target>

Prepare Files $ ant -f config.xml -Dpartner.dir="xxx" -Dpkg.name="xxx" -Dver.code="xxx" -Dver.name="xxx" preparefiles

Create build.xml Build $ ant debug or $ ant release

Upvotes: 2

Fredrik Jonson
Fredrik Jonson

Reputation: 11

I'm using the maven-android-plugin to achieve this. Specify one AndroidManifest.xml for the generated-sources goal and another AndroidManifest.xml for the final apk goal. That way the source code project retains the actual source code package name during generation of the R class and the build phase, while the market adapted manifest package name is in the second AndroidManifest.xml which is included in the final apk file.

Upvotes: 1

Prashast
Prashast

Reputation: 5675

What I did for something similar to this is to just use an antlib task and then go through all java and xml files to replace my old package string to the new package string. It didn't matter if the files were not in the correct src paths according to the package. Just doing a regex replace for all the files was enough for me to get this working...

For example to replace it in all your java files under the src directory:

 <replaceregexp flags="g" byline="false">
    <regexp pattern="old.package.string" /> 
    <substitution expression="new.package.string" />
    <fileset dir="src" includes="**/*.java" /> 
 </replaceregexp>

Upvotes: 6

CommonsWare
CommonsWare

Reputation: 1006554

The linked-to solution does not have to be done by hand. Bear in mind that the package attribute in the <manifest> element does not have to be where the code resides, so long as you spell out the fully-qualified classes elsewhere in the manifest (e.g., activity android:name="com.commonsware.android.MyActivity" rather than activity android:name=".MyActivity"). Script your manifest change and use Ant to build a new APK. AFAIK, that should work.

Upvotes: 4

Related Questions