After an application has been coded and tested, it is necessary to prepare a package for distribution. Preparing the package consists of the following steps:
- Compile For Release – This step involves setting some application attributes.
- Create a Private Key – This step needs to be performed only once. A private key is necessary to digitally sign the APK. After the private key has been prepared, this step can be skipped for future release builds.
- Sign the APK – This step involves signing the APK with the private key that was created in the previous step.
- Zipalign the APK – Zipalign is an optimization process that is performed on an application. It enables Android to interact more efficiently with the APK at runtime. Xamarin.Android conducts a check at runtime, and will not allow the application to run if the APK has not been zipaligned.
The last two steps of preparing an application for release differ in Xamarin Studio and Visual Studio. The difference between these two steps will be covered in more detail below.
Compile the Application for Release
The first step in distribution is to compile the Xamarin.Android application for release. Compiling for release involves:
- Disable Debugging – This prevents users from trying to debug the application on a device by using ADB or other tools.
- Specify the Application Icon – Each Xamarin.Android application should have an application icon specified. It is not technically required; however, some markets, such as Google Play, require it.
- Version the Application – This step involves initializing or updating the versioning information. This is important for future application updates and to ensure that the users are aware of which version of the application they have installed.
- Configure the Linker – Linking is a step that is specific to Xamarin.Android and can substantially reduce the size of the final APK by removing un-used code.
- Compile – This step will compile the code and assets into an APK that is ready for signing.
Each of these steps is described in more detail below.
During development of an Android application, debugging is performed with the use of the Java Debug Wire Protocol (JDWP). This is a technology that allows tools such as ADB to communicate with a JVM for the purposes of debugging. JDWP is turned on by default for Debug builds of a Xamarin.Android application. While JDWP is important during development, it can pose a security issue for released applications.
Always disable the debug state in a released
application as it is possible (via JDWP) to gain full access to the Java
process and execute arbitrary code in the context of the application, if this
debug state is not disabled.Inside the Android manifest exists the attribute
android:debuggable, which controls whether or not the application
may be debugged. It is considered a good practice to set the
The simplest way to do this is by adding a conditional compile statement to
#if DEBUG [assembly: Application(Debuggable=true)] #else [assembly: Application(Debuggable=false)] #endif
Specify The Application Icon
It is strongly recommended that a Xamarin.Android application should specify an application icon. Some application marketplaces will not allow an Android application to be published without one.
Icon property of the
used to specify the application icon for a Xamarin.Android project. This
attribute can be declared in the file
as shown in the sample snippet:
[assembly: Application(Icon = "@drawable/ic_launcher")]
With Xamarin Studio, it is also possible to specify the application icon through the Project Options dialog, under Xamarin.Android Application, as shown in the following screenshot:
The Xamarin.Android plug-in for Visual Studio 2010 does not have this
setting, so the Application Icon must be set by using the
ApplicationAttribute (described above).
Versioning is important for Android application maintenance and distribution. Without some sort of versioning in place, it is difficult to determine if or how an application should be updated.
To assist with versioning, Android recognizes two different types of information. The first is a version code, which is used internally by Android and the application. The second type of information, a version name, is only used for communicating information to the user about the version of the application that is installed on the specific device that is in use.
There are two attributes that are available to provide version information:
- android:versionCode – This is an integer value that represents the version of the application. Most applications start out with this value set to 1, and then it is incremented with each build. This value has no relationship or affinity with the android :v ersionName attribute (see below). Applications and publishing services should not display this value to users.
- android:versionName – This is a string that is meant to be displayed to users or in Google Play. This string is not used internally by Android at all. This can be any string value that would help a user identify the build that is installed on their device.
In Xamarin Studio, these values can be set via Project Options, under the Build… Android Applications tab, as shown in the following screenshot:
In Visual Studio 2013, these values can be set in the Android Manifest section of Project Properties, as shown in the following screenshot:
Compile the Application for Release
In general, applications are developed using Debug mode by default. It will be necessary to change this to Release mode. Release mode turns off the shared runtime and turns on linking so that the application only ships the pieces of Xamarin.Android required at runtime. The linker in Xamarin.Android will use static analysis to determine which assemblies, types, and type members are used or referenced by a Xamarin.Android application. The linker will then discard all the unused assemblies, types, and members that are not used (or referenced). This can result in a significant reduction in the package size. For example, consider the HelloWorld sample, which experienced an 83% reduction in the final size of the APK:
Xamarin.Android 4.2.5 Size
SDK Assemblies Only
In Visual Studio 2013, you set linker options through project properties: Under Android Options, click the Linker tab as shown in the following screen shot:
The Linking pull-down menu provides the following options for controlling the linker:
- None – This turns off the linker; no linking will be performed.
- Sdk Assemblies Only – This will only link the assemblies that are required by Xamarin.Android . Other assemblies will not be linked.
- Sdk and User Assemblies – This will link all assemblies that are required by the application, and not just the ones required by Xamarin.Android.
In Xamarin Studio, you set linker options through the Linker tab of project properties in the Xamarin.Android Build section, as shown in the following screenshot:
The options for controlling the linker are as follows:
- Don't link – This turns off the linker; no linking will be performed.
- Link SDK assemblies only – This will only link the assemblies that are required by Xamarin.Android . Other assemblies will not be linked.
- Link all assemblies – This will link all assemblies that are required by the application, and not just the ones required by Xamarin.Android.
Linking can have some unintended side effects, so it is important that an application be tested in Release mode. The testing must also occur on a physical device.
After configuring the linker, compile the application. Next, you will create a signed APK in conjunction with a private keystore. Xamarin Studio and Visual Studio 2010 have different workflows for signing a keystore; each of these workflows is covered in the following sections.
Creating a Private Keystore
A keystore is a database of security certificates that is created by using the program keytool from the Java SDK. A keystore is critical to publishing a Xamarin.Android application, as Android will not run applications that have not been digitally signed.
During development, Xamarin.Android uses a debug keystore to sign the application, which allows the application to be deployed directly to the emulator or to devices configured to use debuggable applications. However, this keystore is not recognized as a valid keystore for the purposes of distributing applications.
For this reason, a private keystore must be created and used for signing applications. This is a step that should only be performed once, as the same key will be used for publishing updates and can then be used to sign other applications.
It is important to protect this keystore. If it is lost, then it will not be possible to publish updates to the application with Google Play. The only solution to the problem caused by a lost keystore would be to create a new keystore, re-sign the APK with the new key, and then submit a new application. Then the old application would have to be removed from Google Play. Likewise, if this new keystore is compromised or publically distributed, then it is possible for unofficial or malicious versions of an application to be distributed.
Create a New Keystore
Creating a new keystore requires the command line tool keytool from the Java SDK. The following snippet is an
example of how to use
<my-filename> with the file name for the keystore and
<key-name> with the name of the key within the keystore):
$ keytool -genkey -v -keystore <filename>.keystore -alias <key-name> -keyalg RSA -keysize 2048 -validity 10000
The first thing that
keytool will ask for is the password for
the keystore. Then it will ask for some information to help with creating the
key. The following snippet is an example of creating a new key called
publishingdoc that will be stored in the file
$ keytool -genkey -v -keystore xample.keystore -alias publishingdoc -keyalg RSA -keysize 2048 -validity 10000 Enter keystore password: Re-enter new password: What is your first and last name? [Unknown]: Ham Chimpanze What is the name of your organizational unit? [Unknown]: NASA What is the name of your organization? [Unknown]: NASA What is the name of your City or Locality? [Unknown]: Cape Canaveral What is the name of your State or Province? [Unknown]: Florida What is the two-letter country code for this unit? [Unknown]: US Is CN=Ham Chimpanze, OU=NASA, O=NASA, L=Cape Canaveral, ST=Florida, C=US correct? [no]: yes Generating 2,048 bit RSA key pair and self-signed certificate (SHA1withRSA) with a validity of 10,000 days for: CN=Ham Chimpanze, OU=NASA, O=NASA, L=Cape Canaveral, ST=Florida, C=US Enter key password for <publishingdoc> (RETURN if same as keystore password): Re-enter new password: [Storing xample.keystore]
To list the keys that are stored in a keystore, use the
$ keytool -list -keystore xample.keystore
Signing the APK (Xamarin Studio)
The APK found in the
bin/Release folder has been signed
with the debug keystore that is used by Xamarin.Android; therefore,
you should not distribute this APK. Devices will not allow this APK to
be installed and Google Play will not accept it. To create a signed
APK, you must use the unsigned APK in conjunction with a private
Creating a signed APK in Xamarin Studio is done via a series of dialogs that are initiated by switching the build configuration to Release and selecting the Project… Publish Android Application menu item, as shown below:
After selecting this menu item, use the Keystore selection dialog to select a key from a keystore and to provide the password:
After clicking Forward, the Select destination dialog appears. This dialog is used to name the signed APK and to specify the directory where the APK should be created:
When the Create button is clicked, Xamarin Studio compiles the APK, signs it with the key specified, and then runs the zipalign tool against the APK, all in one step.
At this point Xamarin Studio has compiled the Xamarin.Android application into an APK that is ready for distribution.
Signing the APK in Visual Studio (Xamarin.Android 4.2.6 or higher)
Xamarin.Android 4.2.6 introduced a Publish Android Application helper that is similar to the helper process in Xamarin Studio. To publish an application, the build configuration must first be changed to Release. Once the build configuration has been changed, select the Publish Android Application from the Tools menu, as shown in the following screenshot:
After selecting this menu item, use the Publish Android Application dialog to select a key from a keystore and to provide the password:
After clicking Next, the Select destination dialog appears. This dialog is used to name the signed APK and to specify the directory where the APK should be created:
When the Publish button is clicked, Visual Studio compiles the APK, signs it with the key specified, and then runs the zipalign tool against the APK, all in one step.
At this point, Visual Studio has compiled the Xamarin.Android application into an APK that is ready for distribution.
Signing the APK in Visual Studio (pre Xamarin.Android 4.2.6)
Older versions of Xamarin.Android (prior to version 4.2.6) require a more involved process because they lack a Publish Android Application option. The new process involves the following steps:
- Create the
- Sign the
- Zipalign the
To create the APK file, select the menu option Build… Package, as shown in thefollowing screenshot:
This will create two
.apk files in the
folder, as shown in the following screenshot:
mono.samples.helloworld.apk is an unsigned APK, whereas
mono.samples.helloworld–Signed.apk is signed by using
the debug keystore. Because of this, it is not possible to publish
There are two strategies for obtaining a signed APK when using Visual Studio:
- Permanently Use A Different Keystore – By using this technique, the project file is altered to replace the debug keystore with a private keystore. This method is simpler, but poses a security risk.
Manually Signing the APK – This technique involves manually signing the APK at the command line. This is more secure, but requires a little more effort. The amount of effort exerted can be mitigated by using a simple Powershell script. An example of this script is provided later on in this document.
Permanently Use A Different Keystore
To use a different keystore for Release builds
involves modifying the Xamarin.Android
.csproj file and adding an MSBuild condition:
<PropertyGroup Condition="'$(Configuration)' == 'Release'"> <AndroidKeyStore>True</AndroidKeyStore> <AndroidSigningKeyStore>public.keystore</AndroidSigningKeyStore> <AndroidSigningStorePass>MyKeystorePassword</AndroidSigningStorePass> <AndroidSigningKeyAlias>MyKey</AndroidSigningKeyAlias> <AndroidSigningKeyPass>MyKeyPassword</AndroidSigningKeyPass> </PropertyGroup>
The values of the elements in the
PropertyGroup are explained in
the following list:
- AndroidSigningKeystore – This should hold the path and file name of the keystore.
- AndroidSigningStorePass – This holds the password of the keystore.
- AndroidSigningKeyAlias – This contains the name of the key in the keystore that will be used to sign the application.
- AndroidSigningKeyPass – This is the password for the key alias.
As an example, using the keystore that was created above, the MSBuild condition would look as follows:
<PropertyGroup Condition="'$(Configuration)' == 'Release'"> <AndroidKeyStore>True</AndroidKeyStore> <AndroidSigningKeyStore>xample.keystore</AndroidSigningKeyStore> <AndroidSigningStorePass>password</AndroidSigningStorePass> <AndroidSigningKeyAlias>publishingdoc</AndroidSigningKeyAlias> <AndroidSigningKeyPass>password</AndroidSigningKeyPass> </PropertyGroup>
Note: Use this technique with caution as it does store the password for the private key in a plain text file that is easily read by anyone that has access to the source code. This is a potential security risk.
Manually Signing the APK
This technique involves signing the APK file outside of the Visual Studio toolset. The signing is performed at the command line, but can be automated easily by using a scripting language such as Powershell. To manually sign an APK:
- Locate the unsigned APK, as shown earlier .
- Sign the APK using
jarsigner. Once the release APK is built, it is signed by using the jarsigner tool from the Java SDK and the private keystore that was created above. The following shows how to sign an APK by using
jarsignerand the key
publishingdocthat is contained in a keystore file named
$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore xample.keystore mono.samples.helloworld.apk publishingdoc
Zipalign the APK
After an application has been signed, it is important to optimize the APK file. To do this, use the zipalign tool from the Android SDK. The zipalign tool will restructure the resources in an APK along 4-byte boundaries. This alignment allows Android to quickly load the resources from the APK, increasing the performance of the application. Xamarin.Android will conduct a run-time check to determine if the APK has been zipaligned. If the APK is not zipaligned, then the application will not run.
The follow command will use the signed APK and produce a signed, zipaligned
helloworld.apk that is ready for distribution.
$ zipalign -f -v 4 mono.samples.helloworld-Signed.apk helloworld.apk
Signing the APK will undo the optimization that is
Using Powershell to Automate APK signing
Manually signing an APK can prove to be a tedious and error-prone process,
and having to embed the password for the keystore inside the
csproj file does pose security concerns. One possible solution to
this is to create a PowerShell script that can be used to compile the APK, and
then sign it at the command line. Here is an example of what such a PowerShell
script might look like:
# First clean the Release target. msbuild.exe HelloWorld.csproj /p:Configuration=Release /t:Clean # Now build the project, using the Release target. msbuild.exe HelloWorld.csproj /p:Configuration=Release /t:PackageForAndroid # At this point there is only the unsigned APK - sign it. # The script will pause here as jarsigner prompts for the password. # It is possible to provide they keystore password for jarsigner.exe by adding an extra command line parameter -storepass, for example # -storepass <MY_SECRET_PASSWORD> # If this script is to be checked in to source code control then it is not recommended to include the password as part of this script. & 'C:\Program Files\Java\jdk1.6.0_24\bin\jarsigner.exe' -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore ./xample.keystore -signedjar ./bin/Release/mono.samples.helloworld-signed.apk ./bin/Release/mono.samples.helloworld.apk publishingdoc # Now zipalign it. The -v parameter tells zipalign to verify the APK afterwards. & 'C:\Program Files\Android\android-sdk\tools\zipalign.exe' -f -v 4 ./bin/Release/mono.samples.helloworld-signed.apk ./helloworld.apk
After the application has been built for release, it must be published. The following section describes several ways to distribute an application.