Home » Android » android – Is it possible to specify package name dynamically during build?

android – Is it possible to specify package name dynamically during build?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’d like to deploy both Debug and Release builds to my device at the same time. I can do this if I manually change the package name in the manifest before I build, e.g. change

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
          package="my.package">

to

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
          package="my.packageDEBUG">

However, I’d like to do this automatically when I’m building the solution. If I do a Debug build, it’ll build with package="my.packageDEBUG" in the manifest.

Is this possible, and if so, how?

How to&Answers:

You’ll need to create a custom Pre-Build Event for your project.

Right-click on your project and select Properties…

Then click on Build Events and add this to the Pre-build event textbox:

PowerShell -File "$(SolutionDir)Update-PackageName.ps1" $(ProjectDir) $(ConfigurationName)

Copy the following PowerShell script and save it in your solution folder as Update-PackageName.ps1

param ([string] $ProjectDir, [string] $ConfigurationName)
Write-Host "ProjectDir: $ProjectDir"
Write-Host "ConfigurationName: $ConfigurationName"

$ManifestPath = $ProjectDir + "Properties\AndroidManifest.xml"

Write-Host "ManifestPath: $ManifestPath"

[xml] $xdoc = Get-Content $ManifestPath

$package = $xdoc.manifest.package

If ($ConfigurationName -eq "Release" -and $package.EndsWith("DEBUG")) 
{ 
    $package = $package.Replace("DEBUG", "") 
}
If ($ConfigurationName -eq "Debug" -and -not $package.EndsWith("DEBUG")) 
{ 
    $package = $package + "DEBUG" 
}

If ($package -ne $xdoc.manifest.package) 
{
    $xdoc.manifest.package = $package
    $xdoc.Save($ManifestPath)
    Write-Host "AndroidManifest.xml package name updated to $package"
}

Good luck!

Answer:

According to this question on Xamarin’s forum you can change the Packaging Properties and specify different AndroidManifest.xml files for each build.

In the droid.csproj file add the <AndroidManifest> tag like so, for each build configuration:

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    ...
    <AndroidManifest>Properties\AndroidManifestDbg.xml</AndroidManifest>
    ...

Here’s the Xamarin’s documentation on it.