Tuesday, July 19, 2016

How to create a signed and aligned APK using Visual Studio

This article guides you through creating an APK file for your Xamarin.Android App that is ready to publish on Google Play.

Creating an Android APK that is signed and aligned can mostly be achieved with Visual Studio.  To sign it and align it, command line tools must be used, but the APK can be created with Visual Studio.

You're App does need to be signed to be submitted to Google Play, but it doesn't necessarily need to be "aligned".  It is highly recommended however. Its basically a very cheap optimisation that will minimise the amount of RAM your App will need at runtime.

Step 1 - Prepare your App for Release

This is out of scope for this article. Check out this link:

Step 2 - Build a Release build of your App

Build your Android App in Release Mode.  Ensure the platform drop down is set to "Any CPU".

Step 3 - Export to APK

This does not automatically occur when you build a Release build. Creating the APK must be triggered manually by selecting a context menu item when you right click the Android Project in Solution Explorer.

The APK will be created in your bin\Release\ folder for the Android project.

Step 4 - Sign the APK

Ensure you have the JDK path in your environment Path variable.  My JDK is installed here:
C:\Program Files (x86)\Java\jdk1.7.0_55\bin

The "signed" file you see in the folder has been automatically signed with a Developer certificate.  This isn't suitable for publishing purposes, so you'll need a certificate that identifies you as a developer.

To sign your APK, you'll need your Java KeyStore (JKS) file.  These files usually have a JKS extension or a keystore extension.  If you don't have one you can create one using the instructions in the Google reference above. In summary the command line is: keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

Once you have a JKS file you need to keep it in a safe place you must use the same file to sign your App everytime. This file uniquely identifies you as a developer.

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.jks my_application.apk alias_name

There are three things you need to specify in this command:
Replace "my-release-key.jks" with the filename to your JKS file.
Replace "my_application.apk" with your app's APK filename.
Replace the "alias_name" with the alias name you used when creating your JKS file.
You'll also be prompted for the keystore password.

Step 5 - Align the APK

Finally use the Zipalign tool to optimise your APK file.
Zipalign isn't in the same folder as the JDK, for me its in the Android tools folder here:
C:\Program Files (x86)\Android\android-sdk\build-tools\22.0.1
This also should be added to your environment path if it isn't already.

zipalign -v 4 my_application.apk my_application_aligned.apk

That's it.

No comments:

Post a Comment