编译 发布 release的apk

本文由博主原创,转载请注明出处(保留此处和链接):

一日二十四挨踢http://1024it.net/?p=209

 

 


 

编译发布release的apk只需要六步,如下:

1.keytool -genkey -v -keystore robin.keystore -alias robin -keyalg RSA -keysize 2048 -validity 10000
2.ant release
3.jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore robin.keystore bin/show-picture-release-unsigned.apk robin
4.jarsigner -verify bin/show-picture-release-unsigned.apk
5.jarsigner -verify -verbose -certs bin/show-picture-release-unsigned.apk
6.zipalign -v 4 bin/show-picture-release-unsigned.apk bin/show-picture.apk


下面是我要发布为release的apk实例(总共分六步完成操作):

robin@ubuntu:~/workspace/android-ndk-r8/samples/show-picture$ ls
AndroidManifest.xml  assets  build.xml  local.properties  proguard-project.txt  project.properties  res  src


第一步:
robin@ubuntu:~/workspace/android-ndk-r8/samples/show-picture$ keytool -genkey -v -keystore robin.keystore -alias robin -keyalg RSA -keysize 2048 -validity 10000

填写对应信息:
Enter keystore password:  
Re-enter new password: 
What is your first and last name?
  [Unknown]:  Robin Lau
What is the name of your organizational unit?
  [Unknown]:  CST
What is the name of your organization?
  [Unknown]:  CUST
What is the name of your City or Locality?
  [Unknown]:  JILIN
What is the name of your State or Province?
  [Unknown]:  JILIN
What is the two-letter country code for this unit?
  [Unknown]:  86
Is CN=Robin Lau, OU=CST, O=CUST, L=JILIN, ST=JILIN, C=86 correct?
  [no]:  no
What is your first and last name?
  [Robin Lau]:  
What is the name of your organizational unit?
  [CST]:  
What is the name of your organization?
  [CUST]:  
What is the name of your City or Locality?
  [JILIN]:  CC
What is the name of your State or Province?
  [JILIN]:  
What is the two-letter country code for this unit?
  [86]:  
Is CN=Robin Lau, OU=CST, O=CUST, L=CC, ST=JILIN, C=86 correct?
  [no]:  yes

Generating 2,048 bit RSA key pair and self-signed certificate (SHA1withRSA) with a validity of 10,000 days
	for: CN=Robin Lau, OU=CST, O=CUST, L=CC, ST=JILIN, C=86
Enter key password for <robin>
	(RETURN if same as keystore password):  
Key password is too short - must be at least 6 characters
Enter key password for <robin>
	(RETURN if same as keystore password):  
Re-enter new password: 
[Storing robin.keystore]


生成了密钥(robin.keystore)
robin@ubuntu:~/workspace/android-ndk-r8/samples/show-picture$ ls
AndroidManifest.xml  build.xml         proguard-project.txt  res             src
assets               local.properties  project.properties    robin.keystore


第二步:
robin@ubuntu:~/workspace/android-ndk-r8/samples/show-picture$ ant release

Buildfile: /home/robin/workspace/android-ndk-r8/samples/show-picture/build.xml

-set-mode-check:

-set-release-mode:

-release-obfuscation-check:
     [echo] proguard.config is ${proguard.config}

-check-env:
 [checkenv] Android SDK Tools Revision 21
 [checkenv] Installed at /home/robin/workspace/android-sdk-linux_x86

-setup:
     [echo] Project Name: show-picture
  [gettype] Project Type: Application

-build-setup:
     [echo] Resolving Build Target for show-picture...
[gettarget] Project Target:   Android 4.0.3
[gettarget] API level:        15
     [echo] ----------
     [echo] Creating output directories if needed...
    [mkdir] Created dir: /home/robin/workspace/android-ndk-r8/samples/show-picture/libs
    [mkdir] Created dir: /home/robin/workspace/android-ndk-r8/samples/show-picture/bin
    [mkdir] Created dir: /home/robin/workspace/android-ndk-r8/samples/show-picture/bin/res
    [mkdir] Created dir: /home/robin/workspace/android-ndk-r8/samples/show-picture/gen
    [mkdir] Created dir: /home/robin/workspace/android-ndk-r8/samples/show-picture/bin/classes
    [mkdir] Created dir: /home/robin/workspace/android-ndk-r8/samples/show-picture/bin/dexedLibs
     [echo] ----------
     [echo] Resolving Dependencies for show-picture...
[dependency] Library dependencies:
[dependency] No Libraries
[dependency] 
[dependency] ------------------
[dependency] API<=15: Adding annotations.jar to the classpath.
     [echo] ----------
     [echo] Building Libraries with 'release'...
   [subant] No sub-builds to iterate on

-pre-build:

-code-gen:
[mergemanifest] Merging AndroidManifest files into one.
[mergemanifest] Manifest merger disabled. Using project manifest only.
     [echo] Handling aidl files...
     [aidl] No AIDL files to compile.
     [echo] ----------
     [echo] Handling RenderScript files...
[renderscript] No RenderScript files to compile.
     [echo] ----------
     [echo] Handling Resources...
     [aapt] Generating resource IDs...
     [echo] ----------
     [echo] Handling BuildConfig class...
[buildconfig] Generating BuildConfig class.

-pre-compile:

-compile:
    [javac] Compiling 3 source files to /home/robin/workspace/android-ndk-r8/samples/show-picture/bin/classes

-post-compile:

-obfuscate:

-dex:
      [dex] input: /home/robin/workspace/android-ndk-r8/samples/show-picture/bin/classes
      [dex] input: /home/robin/workspace/android-sdk-linux_x86/tools/support/annotations.jar
      [dex] Pre-Dexing /home/robin/workspace/android-sdk-linux_x86/tools/support/annotations.jar -> annotations-f49130f27e2660ecdc94e6445bd67dd5.jar
      [dex] Converting compiled files and external libraries into /home/robin/workspace/android-ndk-r8/samples/show-picture/bin/classes.dex...
       [dx] Merged dex A (9 defs/4.2KiB) with dex B (2 defs/1.1KiB). Result is 11 defs/5.4KiB. Took 0.1s

-crunch:
   [crunch] Crunching PNG Files in source dir: /home/robin/workspace/android-ndk-r8/samples/show-picture/res
   [crunch] To destination dir: /home/robin/workspace/android-ndk-r8/samples/show-picture/bin/res
   [crunch] Processing image to cache: /home/robin/workspace/android-ndk-r8/samples/show-picture/res/drawable/icon.png => /home/robin/workspace/android-ndk-r8/samples/show-picture/bin/res/drawable/icon.png
   [crunch]   (processed image to cache entry /home/robin/workspace/android-ndk-r8/samples/show-picture/bin/res/drawable/icon.png: 0% size of source)
   [crunch] Crunched 1 PNG files to update cache

-package-resources:
     [aapt] Creating full resource package...

-package:
[apkbuilder] Current build type is different than previous build: forced apkbuilder run.
[apkbuilder] Creating show-picture-release-unsigned.apk for release...

-post-package:

-release-prompt-for-password:

-release-nosign:
     [echo] No key.store and key.alias properties found in build.properties.
     [echo] Please sign /home/robin/workspace/android-ndk-r8/samples/show-picture/bin/show-picture-release-unsigned.apk manually
     [echo] and run zipalign from the Android SDK tools.
[propertyfile] Creating new property file: /home/robin/workspace/android-ndk-r8/samples/show-picture/bin/build.prop
[propertyfile] Updating property file: /home/robin/workspace/android-ndk-r8/samples/show-picture/bin/build.prop
[propertyfile] Updating property file: /home/robin/workspace/android-ndk-r8/samples/show-picture/bin/build.prop
[propertyfile] Updating property file: /home/robin/workspace/android-ndk-r8/samples/show-picture/bin/build.prop

-release-sign:

-post-build:

release:

BUILD SUCCESSFUL
Total time: 5 seconds

robin@ubuntu:~/workspace/android-ndk-r8/samples/show-picture$ ls
AndroidManifest.xml  bin        gen   local.properties      project.properties  robin.keystore
assets               build.xml  libs  proguard-project.txt  res                 src


第三步:
robin@ubuntu:~/workspace/android-ndk-r8/samples/show-picture$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore robin.keystore bin/show-picture-release-unsigned.apk robin
Enter Passphrase for keystore: 
   adding: META-INF/MANIFEST.MF
   adding: META-INF/ROBIN.SF
   adding: META-INF/ROBIN.RSA
  signing: assets/p03.jpg
  signing: res/drawable/icon.png
  signing: res/layout/showmyself.xml
  signing: AndroidManifest.xml
  signing: resources.arsc
  signing: classes.dex


第四步:
robin@ubuntu:~/workspace/android-ndk-r8/samples/show-picture$ jarsigner -verify bin/show-picture-release-unsigned.apk
jar verified.

第五步:
robin@ubuntu:~/workspace/android-ndk-r8/samples/show-picture$ jarsigner -verify -verbose -certs bin/show-picture-release-unsigned.apk

         493 Sat Aug 10 05:05:46 CST 2013 META-INF/MANIFEST.MF
         614 Sat Aug 10 05:05:46 CST 2013 META-INF/ROBIN.SF
        1276 Sat Aug 10 05:05:46 CST 2013 META-INF/ROBIN.RSA
sm     10128 Tue Jul 09 09:51:20 CST 2013 assets/p03.jpg

      X.509, CN=Robin Lau, OU=CST, O=CUST, L=CC, ST=JILIN, C=86
      [certificate is valid from 8/10/13 5:02 AM to 12/26/40 5:02 AM]

sm      2200 Sat Aug 10 05:03:52 CST 2013 res/drawable/icon.png

      X.509, CN=Robin Lau, OU=CST, O=CUST, L=CC, ST=JILIN, C=86
      [certificate is valid from 8/10/13 5:02 AM to 12/26/40 5:02 AM]

sm       740 Sat Aug 10 05:03:52 CST 2013 res/layout/showmyself.xml

      X.509, CN=Robin Lau, OU=CST, O=CUST, L=CC, ST=JILIN, C=86
      [certificate is valid from 8/10/13 5:02 AM to 12/26/40 5:02 AM]

sm      1412 Sat Aug 10 05:03:52 CST 2013 AndroidManifest.xml

      X.509, CN=Robin Lau, OU=CST, O=CUST, L=CC, ST=JILIN, C=86
      [certificate is valid from 8/10/13 5:02 AM to 12/26/40 5:02 AM]

sm      1096 Sat Aug 10 05:03:52 CST 2013 resources.arsc

      X.509, CN=Robin Lau, OU=CST, O=CUST, L=CC, ST=JILIN, C=86
      [certificate is valid from 8/10/13 5:02 AM to 12/26/40 5:02 AM]

sm      5564 Sat Aug 10 05:03:50 CST 2013 classes.dex

      X.509, CN=Robin Lau, OU=CST, O=CUST, L=CC, ST=JILIN, C=86
      [certificate is valid from 8/10/13 5:02 AM to 12/26/40 5:02 AM]


  s = signature was verified 
  m = entry is listed in manifest
  k = at least one certificate was found in keystore
  i = at least one certificate was found in identity scope

jar verified.


第六步:
robin@ubuntu:~/workspace/android-ndk-r8/samples/show-picture$ zipalign -v 4 bin/show-picture-release-unsigned.apk bin/show-picture.apk
Verifying alignment of bin/show-picture.apk (4)...
      50 META-INF/MANIFEST.MF (OK - compressed)
     440 META-INF/ROBIN.SF (OK - compressed)
     896 META-INF/ROBIN.RSA (OK - compressed)
    2012 assets/p03.jpg (OK)
   12192 res/drawable/icon.png (OK)
   14447 res/layout/showmyself.xml (OK - compressed)
   14858 AndroidManifest.xml (OK - compressed)
   15468 resources.arsc (OK)
   16605 classes.dex (OK - compressed)
Verification succesful

到此为止,release的apk生成了。切记,在上面操作之前,一定要先生成so文件,即,ndkb-build



Eclipse Users


If you are developing in Eclipse/ADT (and have set up Keytool and Jarsigner as described above in Basic Setup for Signing), signing in debug mode is enabled by default. When you run or debug your application, ADT signs the .apk file with the debug certificate, runs zipalign on the package, then installs it on the selected emulator or connected device. No specific action on your part is needed, provided ADT has access to Keytool.

Ant Users

If you are using Ant to build your .apk file, debug signing mode is enabled by using the debug option with the antcommand (assuming that you are using a build.xml file generated by the android tool). When you run ant debug to compile your app, the build script generates a keystore/key and signs the APK for you. The script then also aligns the APK with the zipalign tool. No other action on your part is needed. Read Building and Running Apps on the Command Line for more information.

Expiry of the Debug Certificate

The self-signed certificate used to sign your application in debug mode (the default on Eclipse/ADT and Ant builds) will have an expiration date of 365 days from its creation date.

When the certificate expires, you will get a build error. On Ant builds, the error looks like this:

debug:
[echo] Packaging bin/samples-debug.apk, and signing it with a debug key...
[exec] Debug Certificate expired on 8/4/08 3:43 PM

In Eclipse/ADT, you will see a similar error in the Android console.

To fix this problem, simply delete the debug.keystore file. The default storage location for AVDs is in ~/.android/ on OS X and Linux, in C:\Documents and Settings\<user>\.android\ on Windows XP, and in C:\Users\<user>\.android\ on Windows Vista and Windows 7.

The next time you build, the build tools will regenerate a new keystore and debug key.

Note that, if your development machine is using a non-Gregorian locale, the build tools may erroneously generate an already-expired debug certificate, so that you get an error when trying to compile your application. For workaround information, see the troubleshooting topic I can't compile my app because the build tools generated an expired debug certificate.

Signing in Release Mode


When your application is ready for release to other users, you must:

  1. Obtain a suitable private key
  2. Compile the application in release mode
  3. Sign your application with your private key
  4. Align the final APK package

If you are developing in Eclipse with the ADT plugin, you can use the Export Wizard to perform the compile, sign, and align procedures. The Export Wizard even allows you to generate a new keystore and private key in the process. So if you use Eclipse, you can skip to Compile and sign with Eclipse ADT.

1. Obtain a suitable private key

In preparation for signing your application, you must first ensure that you have a suitable private key with which to sign. A suitable private key is one that:

  • Is in your possession
  • Represents the personal, corporate, or organizational entity to be identified with the application
  • Has a validity period that exceeds the expected lifespan of the application or application suite. A validity period of more than 25 years is recommended.

    If you plan to publish your application(s) on Google Play, note that a validity period ending after 22 October 2033 is a requirement. You can not upload an application if it is signed with a key whose validity expires before that date.

  • Is not the debug key generated by the Android SDK tools.

The key may be self-signed. If you do not have a suitable key, you must generate one using Keytool. Make sure that you have Keytool available, as described in Basic Setup.

To generate a self-signed key with Keytool, use the keytool command and pass any of the options listed below (and any others, as needed).

Warning: Keep your private key secure. Before you run Keytool, make sure to read Securing Your Private Key for a discussion of how to keep your key secure and why doing so is critically important to you and to users. In particular, when you are generating your key, you should select strong passwords for both the keystore and key.

Warning: Keep the keystore file you generate with Keytool in a safe, secure place. You must use the same key to sign future versions of your application. If you republish your app with a new key, Google Play will consider it a new app. For more information on settings that must remain constant over the life of your app, see the Android Developer Blog postThings That Cannot Change.

Keytool Option Description
-genkey Generate a key pair (public and private keys)
-v Enable verbose output.
-alias <alias_name> An alias for the key. Only the first 8 characters of the alias are used.
-keyalg <alg> The encryption algorithm to use when generating the key. Both DSA and RSA are supported.
-keysize <size> The size of each generated key (bits). If not supplied, Keytool uses a default key size of 1024 bits. In general, we recommend using a key size of 2048 bits or higher.
-dname <name>

A Distinguished Name that describes who created the key. The value is used as the issuer and subject fields in the self-signed certificate.

Note that you do not need to specify this option in the command line. If not supplied, Jarsigner prompts you to enter each of the Distinguished Name fields (CN, OU, and so on).

-keypass <password>

The password for the key.

As a security precaution, do not include this option in your command line. If not supplied, Keytool prompts you to enter the password. In this way, your password is not stored in your shell history.

-validity <valdays>

The validity period for the key, in days.

Note: A value of 10000 or greater is recommended.

-keystore <keystore-name>.keystore A name for the keystore containing the private key.
-storepass <password>

A password for the keystore.

As a security precaution, do not include this option in your command line. If not supplied, Keytool prompts you to enter the password. In this way, your password is not stored in your shell history.

Here's an example of a Keytool command that generates a private key:

$ keytool -genkey -v -keystore my-release-key.keystore
-alias alias_name -keyalg RSA -keysize 2048 -validity 10000

Running the example command above, Keytool prompts you to provide passwords for the keystore and key, and to provide the Distinguished Name fields for your key. It then generates the keystore as a file called my-release-key.keystore. The keystore and key are protected by the passwords you entered. The keystore contains a single key, valid for 10000 days. The alias is a name that you — will use later, to refer to this keystore when signing your application.

For more information about Keytool, see the documentation athttp://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html

2. Compile the application in release mode

In order to release your application to users, you must compile it in release mode. In release mode, the compiled application is not signed by default and you will need to sign it with your private key.

Caution: You can not release your application unsigned, or signed with the debug key.

With Eclipse

To export an unsigned APK from Eclipse, right-click the project in the Package Explorer and select Android Tools > Export Unsigned Application Package. Then specify the file location for the unsigned APK. (Alternatively, open yourAndroidManifest.xml file in Eclipse, select the Manifest tab, and click Export an unsigned APK.)

Note that you can combine the compiling and signing steps with the Export Wizard. See Compiling and signing with Eclipse ADT.

With Ant

If you are using Ant, you can enable release mode by using the release option with the ant command. For example, if you are running Ant from the directory containing your build.xml file, the command would look like this:

$ ant release

By default, the build script compiles the application APK without signing it. The output file in your project bin/ will be<your_project_name>-unsigned.apk. Because the application APK is still unsigned, you must manually sign it with your private key and then align it using zipalign.

However, the Ant build script can also perform the signing and aligning for you, if you have provided the path to your keystore and the name of your key alias in the project's ant.properties file. With this information provided, the build script will prompt you for your keystore and alias password when you perform ant release, it will sign the package and then align it. The final output file in bin/ will instead be <your_project_name>-release.apk. With these steps automated for you, you're able to skip the manual procedures below (steps 3 and 4). To learn how to specify your keystore and alias in the ant.properties file, see Building and Running Apps on the Command Line.

3. Sign your application with your private key

When you have an application package that is ready to be signed, you can do sign it using the Jarsigner tool. Make sure that you have Jarsigner available on your machine, as described in Basic Setup. Also, make sure that the keystore containing your private key is available.

To sign your application, you run Jarsigner, referencing both the application's APK and the keystore containing the private key with which to sign the APK. The table below shows the options you could use.

Jarsigner Option Description
-keystore <keystore-name>.keystore The name of the keystore containing your private key.
-verbose Enable verbose output.
-sigalg The name of the signature algorithim to use in signing the APK. Use the value SHA1withRSA.
-digestalg The message digest algorithim to use in processing the entries of an APK. Use the valueSHA1.
-storepass <password>

The password for the keystore.

As a security precaution, do not include this option in your command line unless you are working at a secure computer. If not supplied, Jarsigner prompts you to enter the password. In this way, your password is not stored in your shell history.

-keypass <password>

The password for the private key.

As a security precaution, do not include this option in your command line unless you are working at a secure computer. If not supplied, Jarsigner prompts you to enter the password. In this way, your password is not stored in your shell history.

Here's how you would use Jarsigner to sign an application package called my_application.apk, using the example keystore created above.

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

Running the example command above, Jarsigner prompts you to provide passwords for the keystore and key. It then modifies the APK in-place, meaning the APK is now signed. Note that you can sign an APK multiple times with different keys.

Caution: As of JDK 7, the default signing algorithim has changed, requiring you to specify the signature and digest algorithims (-sigalg and -digestalg) when you sign an APK.

To verify that your APK is signed, you can use a command like this:

$ jarsigner -verify my_signed.apk

If the APK is signed properly, Jarsigner prints "jar verified". If you want more details, you can try one of these commands:

$ jarsigner -verify -verbose my_application.apk

or

$ jarsigner -verify -verbose -certs my_application.apk

The command above, with the -certs option added, will show you the "CN=" line that describes who created the key.

Note: If you see "CN=Android Debug", this means the APK was signed with the debug key generated by the Android SDK. If you intend to release your application, you must sign it with your private key instead of the debug key.

For more information about Jarsigner, see the documentation athttp://docs.oracle.com/javase/6/docs/technotes/tools/windows/jarsigner.html

4. Align the final APK package

Once you have signed the APK with your private key, run zipalign on the file. This tool ensures that all uncompressed data starts with a particular byte alignment, relative to the start of the file. Ensuring alignment at 4-byte boundaries provides a performance optimization when installed on a device. When aligned, the Android system is able to read files with mmap(), even if they contain binary data with alignment restrictions, rather than copying all of the data from the package. The benefit is a reduction in the amount of RAM consumed by the running application.

The zipalign tool is provided with the Android SDK, inside the tools/ directory. To align your signed APK, execute:

$ zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk

The -v flag turns on verbose output (optional). 4 is the byte-alignment (don't use anything other than 4). The first file argument is your signed .apk file (the input) and the second file is the destination .apk file (the output). If you're overriding an existing APK, add the -f flag.

Caution: Your input APK must be signed with your private key before you optimize the package with zipalign. If you sign it after using zipalign, it will undo the alignment.

For more information, read about the zipalign tool.

Compile and sign with Eclipse ADT

If you are using Eclipse with the ADT plugin, you can use the Export Wizard to export a signed APK (and even create a new keystore, if necessary). The Export Wizard performs all the interaction with the Keytool and Jarsigner for you, which allows you to sign the package using a GUI instead of performing the manual procedures to compile, sign, and align, as discussed above. Once the wizard has compiled and signed your package, it will also perfom package alignment withzipalign. Because the Export Wizard uses both Keytool and Jarsigner, you should ensure that they are accessible on your computer, as described above in the Basic Setup for Signing.

To create a signed and aligned APK in Eclipse:

  1. Select the project in the Package Explorer and select File > Export.
  2. Open the Android folder, select Export Android Application, and click Next.

    The Export Android Application wizard now starts, which will guide you through the process of signing your application, including steps for selecting the private key with which to sign the APK (or creating a new keystore and private key).

  3. Complete the Export Wizard and your application will be compiled, signed, aligned, and ready for distribution.

Securing Your Private Key


Maintaining the security of your private key is of critical importance, both to you and to the user. If you allow someone to use your key, or if you leave your keystore and passwords in an unsecured location such that a third-party could find and use them, your authoring identity and the trust of the user are compromised.

If a third party should manage to take your key without your knowledge or permission, that person could sign and distribute applications that maliciously replace your authentic applications or corrupt them. Such a person could also sign and distribute applications under your identity that attack other applications or the system itself, or corrupt or steal user data.

Your private key is required for signing all future versions of your application. If you lose or misplace your key, you will not be able to publish updates to your existing application. You cannot regenerate a previously generated key.

Your reputation as a developer entity depends on your securing your private key properly, at all times, until the key is expired. Here are some tips for keeping your key secure:

  • Select strong passwords for the keystore and key.
  • When you generate your key with Keytool, do not supply the -storepass and -keypass options at the command line. If you do so, your passwords will be available in your shell history, which any user on your computer could access.
  • Similarly, when signing your applications with Jarsigner, do not supply the -storepass and -keypass options at the command line.
  • Do not give or lend anyone your private key, and do not let unauthorized persons know your keystore and key passwords.
  • Keep the keystore file containing your private key that you generate with the Keytool in a safe, secure place.

In general, if you follow common-sense precautions when generating, using, and storing your key, it will remain secure.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值