Publishing Overview

本文详细介绍了Android应用从准备到发布的全过程,包括配置、构建、测试、发布等步骤,以及如何选择合适的证书、设置最小系统API版本、进行版本管理等关键环节。同时,文章还强调了安全性的重要性,如保护私钥、避免使用过期证书等,确保应用能够顺利发布并受到用户信任。

http://developer.android.com/tools/publishing/publishing_overview.html


Publishing is the general process that makes your Android applications available to users. When you publish an Android application you perform two main tasks:

  • You prepare the application for release.

    During the preparation step you build a release version of your application, which users can download and install on their Android-powered devices.

  • You release the application to users.

    During the release step you publicize, sell, and distribute the release version of your application to users.

Usually, you release your application through an application marketplace, such as Google Play. However, you can also release applications by sending them directly to users or by letting users download them from your own website.

Figure 1 shows how the publishing process fits into the overall Androidapplication development process. The publishing process is typically performed after you finish testing your application in a debug environment. Also, as a best practice, your application should meet all of your release criteria for functionality, performance, and stability before you begin the publishing process.

Shows where the publishing       process fits into the overall development process

Figure 1. Publishing is the last phase of the Android application development process.

Preparing Your Application for Release


Preparing your application for release is a multi-step process that involves the following tasks:

  • Configuring your application for release.

    At a minimum you need to remove Log calls and remove the android:debuggable attribute from your manifest file. You should also provide values for the android:versionCode and android:versionName attributes, which are located in the<manifest> element. You may also have to configure several other settings to meet Google Play requirements or accomodate whatever method you're using to release your application.

  • Building and signing a release version of your application.

    The Android Development Tools (ADT) plugin and the Ant build script that are provided with the Android SDK tools provide everything you need to build and sign a release version of your application.

  • Testing the release version of your application.

    Before you distribute your application, you should thoroughly test the release version on at least one target handset device and one target tablet device.

  • Updating application resources for release.

    You need to be sure that all application resources such as multimedia files and graphics are updated and included with your application or staged on the proper production servers.

  • Preparing remote servers and services that your application depends on.

    If your application depends on external servers or services, you need to be sure they are secure and production ready.

You may have to perform several other tasks as part of the preparation process. For example, you will need to get a private key for signing your application, and you may need to get a Maps API release key if you are using the Google Maps external library. You will also need to create an icon for your application, and you may want to prepare an End User License Agreement (EULA) to protect your person, organization, and intellectual property.

When you are finished preparing your application for release you will have a signed .apk file that you can distribute to users.

To learn how to prepare your application for release, see Preparing for Release in the Dev Guide. This topic provides step-by-step instructions for configuring and building a release version of your application.

Releasing Your Application to Users


You can release your Android applications several ways. Usually, you release applications through an application marketplace such as Google Play, but you can also release applications on your own website or by sending an application directly to a user.

Releasing through an App Marketplace

If you want to distribute your apps to the broadest possible audience, releasing through an app marketplace such as Google Play is ideal.

Google Play is the premier marketplace for Android apps and is particularly useful if you want to distribute your applications to a large global audience. However, you can distribute your apps through any app marketplace you want or you can use multiple marketplaces.

Releasing Your Applications on Google Play

Google Play is a robust publishing platform that helps you publicize, sell, and distribute your Android applications to users around the world. When you release your applications through Google Play you have access to a suite of developer tools that let you analyze your sales, identify market trends, and control who your applications are being distributed to. You also have access to several revenue-enhancing features such as in-app billing and application licensing. The rich array of tools and features, coupled with numerous end-user community features, makes Google Play the premier marketplace for selling and buying Android applications.

Releasing your application on Google Play is a simple process that involves three basic steps:

  • Preparing promotional materials.

    To fully leverage the marketing and publicity capabilities of Google Play, you need to create promotional materials for your application, such as screenshots, videos, graphics, and promotional text.

  • Configuring options and uploading assets.

    Google Play lets you target your application to a worldwide pool of users and devices. By configuring various Google Play settings, you can choose the countries you want to reach, the listing languages you want to use, and the price you want to charge in each country. You can also configure listing details such as the application type, category, and content rating. When you are done configuring options you can upload your promotional materials and your application as a draft (unpublished) application.

  • Publishing the release version of your application.

    If you are satisfied that your publishing settings are correctly configured and your uploaded application is ready to be released to the public, you can simply click Publish in the developer console and within minutes your application will be live and available for download around the world.

For information complete information, see Google Play.

Releasing your application through email

Screenshot showing the graphical user interface users see when you send them an app

Figure 1. Users can simply click Installwhen you send them an application via email.

The easiest and quickest way to release your application is to send it to a user through email. To do this, you prepare your application for release and then attach it to an email and send it to a user. When the user opens your email message on their Android-powered device the Android system will recognize the APK and display an Install Now button in the email message (see figure 1). Users can install your application by touching the button.

Note: The Install Now button shown in Figure 1 appears only if a user has configured their device to allow installation from unknown sources and has opened your email with the native Gmail application.

Distributing applications through email is convenient if you are sending your application to only a few trusted users, but it provides few protections from piracy and unauthorized distribution; that is, anyone you send your application to can simply forward it to someone else.

Releasing through a web site


If you do not want to release your app on a marketplace like Google Play, you can make the app available for download on your own website or server, including on a private or enterprise server. To do this, you must first prepare your application for release in the normal way. Then all you need to do is host the release-ready APK file on your website and provide a download link to users.

When users browse to the download link from their Android-powered devices, the file is downloaded and Android system automatically starts installing it on the device. However, the installation process will start automatically only if the user has configured their Settings to allow the installation of apps from unknown sources.

Although it is relatively easy to release your application on your own website, it can be inefficient. For example, if you want to monetize your application you will have to process and track all financial transactions yourself and you will not be able to use Google Play's In-app Billing service to sell in-app products. In addition, you will not be able to use theLicensing service to help prevent unauthorized installation and use of your application.

User Opt-In for Apps from Unknown Sources


Screenshot showing the setting for accepting download and install of       apps from unknown sources.

Figure 2. Users must enable the Unknown sources setting before they can install apps not downloaded from Google Play.

Android protects users from inadvertent download and install of apps from locations other than Google Play (which is trusted). It blocks such installs until the user opts-in Unknown sources in Settings > Security, shown in Figure 2. To allow the installation of applications from other sources, users need to enable the Unknown sources setting on their devices, and they need to make this configuration change before they download your application to their devices.

Note that some network providers do not allow users to install applications from unknown sources.

Preparing for Release

QUICKVIEW

  • Learn which resources you'll need to release your app.
  • Find out how to configure and build your app for release.
  • Learn best practices for releasing your app.

IN THIS DOCUMENT

  1. Introduction
  2. Gathering Materials and Resources
  3. Configuring Your Application
  4. Building Your Application
  5. Preparing External Servers and Resources
  6. Testing Your Application for Release

SEE ALSO

  1. Publishing Overview
  2. Signing Your Applications
  3. Launch Checklist for Google Play

Before you distribute your Android application to users you need to prepare it for release. The preparation process is a required development task for all Android applications and is the first step in the publishing process (see figure 1).

When you prepare your application for release, you configure, build, and test a release version of your application. The configuration tasks are straightforward, involving basic code cleanup and code modification tasks that help optimize your application. The build process is similar to the debug build process and can be done using JDK and Android SDK tools. The testing tasks serve as a final check, ensuring that your application performs as expected under real-world conditions. When you are finished preparing your application for release you have a signed .apk file, which you can distribute directly to users or distribute through an application marketplace such as Google Play.

This document summarizes the main tasks you need to perform to prepare your application for release. The tasks that are described in this document apply to all Android applications regardless how they are released or distributed to users. If you are releasing your application through Google Play, you should also read Publishing Checklist for Google Play to be sure your release-ready application satisfies all Google Play requirements.

Note: As a best practice, your application should meet all of your release criteria for functionality, performance, and stability before you perform the tasks outlined in this document.

Shows how the preparation process fits into the development process

Figure 1. Preparing for release is a required development task and is the first step in the publishing process.

Introduction


To release your application to users you need to create a release-ready package that users can install and run on their Android-powered devices. The release-ready package contains the same components as the debug .apk file — compiled source code, resources, manifest file, and so on — and it is built using the same build tools. However, unlike the debug.apk file, the release-ready .apk file is signed with your own certificate and it is optimized with the zipalign tool.

Shows the five tasks you perform to prepare your app for release

Figure 2. You perform five main tasks to prepare your application for release.

The signing and optimization tasks are usually seamless if you are building your application with Eclipse and the ADT plugin or with the Ant build script (included with the Android SDK). For example, you can use the Eclipse Export Wizard to compile, sign, and optimize your application all at once. You can also configure the Ant build script to do the same when you build from the command line.

To prepare your application for release you typically perform five main tasks (see figure 2). Each main task may include one or more smaller tasks depending on how you are releasing your application. For example, if you are releasing your application through Google Play you may want to add special filtering rules to your manifest while you are configuring your application for release. Similarly, to meet Google Play publishing guidelines you may have to prepare screenshots and create promotional text while you are gathering materials for release.

You usually perform the tasks listed in figure 2 after you have throroughly debugged and tested your application. The Android SDK contains several tools to help you test and debug your Android applications. For more information, see the Debuggingand Testing sections in the Dev Guide.

Gathering Materials and Resources


To begin preparing your application for release you need to gather several supporting items. At a minimum this includes cryptographic keys for signing your application and an application icon. You might also want to include an end-user license agreement.

Cryptographic keys

The Android system requires that each installed application be digitally signed with a certificate that is owned by the application's developer (that is, a certificate for which the developer holds the private key). The Android system uses the certificate as a means of identifying the author of an application and establishing trust relationships between applications. The certificate that you use for signing does not need to be signed by a certificate authority; the Android system allows you to sign your applications with a self-signed certificate. To learn about certificate requirements, seeObtain a suitable private key.

Important: Your application must be signed with a cryptographic key whose validity period ends after 22 October 2033.

You may also have to obtain other release keys if your application accesses a service or uses a third-party library that requires you to use a key that is based on your private key. For example, if your application uses the MapView class, which is part of the Google Maps external library, you will need to register your application with the Google Maps service and obtain a Maps API key. For information about getting a Maps API key, see Obtaining a Maps API key.

Application Icon

Be sure you have an application icon and that it meets the recommended icon guidelines. Your application's icon helps users identify your application on a device's Home screen and in the Launcher window. It also appears in Manage Applications, My Downloads, and elsewhere. In addition, publishing services such as Google Play display your icon to users.

Note: If you are releasing your application on Google Play, you need to create a high resolution version of your icon. SeeGraphic Assets for your Application for more information.

End-user License Agreement

Consider preparing an End User License Agreement (EULA) for your application. A EULA can help protect your person, organization, and intellectual property, and we recommend that you provide one with your application.

Miscellaneous Materials

You might also have to prepare promotional and marketing materials to publicize your application. For example, if you are releasing your application on Google Play you will need to prepare some promotional text and you will need to create screenshots of your application. For more information, see Graphic Assets for your Application

Configuring Your Application for Release


After you gather all of your supporting materials you can start configuring your application for release. This section provides a summary of the configuration changes we recommend that you make to your source code, resource files, and application manifest prior to releasing your application. Although most of the configuration changes listed in this section are optional, they are considered good coding practices and we encourage you to implement them. In some cases, you may have already made these configuration changes as part of your development process.

Choose a good package name

Make sure you choose a package name that is suitable over the life of your application. You cannot change the package name after you distribute your application to users. You can set the package name in application's manifest file. For more information, see the package attribute documentation.

Turn off logging and debugging

Make sure you deactivate logging and disable the debugging option before you build your application for release. You can deactivate logging by removing calls to Log methods in your source files. You can disable debugging by removing theandroid:debuggable attribute from the <application> tag in your manifest file, or by setting the android:debuggableattribute to false in your manifest file. Also, remove any log files or static test files that were created in your project.

Also, you should remove all Debug tracing calls that you added to your code, such as startMethodTracing() andstopMethodTracing() method calls.

Clean up your project directories

Clean up your project and make sure it conforms to the directory structure described in Android Projects. Leaving stray or orphaned files in your project can prevent your application from compiling and cause your application to behave unpredictably. At a minimum you should do the following cleanup tasks:

  • Review the contents of your jni/lib/, and src/ directories. The jni/ directory should contain only source files associated with the Android NDK, such as .c.cpp.h, and .mk files. The lib/ directory should contain only third-party library files or private library files, including prebuilt shared and static libraries (for example, .so files). The src/directory should contain only the source files for your application (.java and .aidl files). The src/ directory should not contain any .jar files.
  • Check your project for private or proprietary data files that your application does not use and remove them. For example, look in your project's res/ directory for old drawable files, layout files, and values files that you are no longer using and delete them.
  • Check your lib/ directory for test libraries and remove them if they are no longer being used by your application.
  • Review the contents of your assets/ directory and your res/raw/ directory for raw asset files and static files that you need to update or remove prior to release.
Review and update your manifest settings

Verify that the following manifest items are set correctly:

  • <uses-permission> element

    You should specify only those permissions that are relevant and required for your application.

  • android:icon and android:label attributes

    You must specify values for these attributes, which are located in the <application> element.

  • android:versionCode and android:versionName attributes.

    We recommend that you specify values for these attributes, which are located in the <manifest> element. For more information see Versioning your Application.

There are several additional manifest elements that you can set if you are releasing your application on Google Play. For example, the android:minSdkVersion and android:targetSdkVersion attributes, which are located in the <uses-sdk>element. For more information about these and other Google Play settings, see Filters on Google Play.

Address compatibility issues

Android provides several tools and techniques to make your application compatible with a wide range of devices. To make your application available to the largest number of users, consider doing the following:

  • Add support for multiple screen configurations

    Make sure you meet the best practices for supporting multiple screens. By supporting multiple screen configurations you can create an application that functions properly and looks good on any of the screen sizes supported by Android.

  • Optimize your application for Android tablet devices.

    If your application is designed for devices older than Android 3.0, make it compatible with Android 3.0 devices by following the guidelines and best practices described in Optimizing Apps for Android 3.0 .

  • Consider using the Support Library

    If your application is designed for devices running Android 3.x, make your application compatible with older versions of Android by adding the Support Library to your application project. The Support Library provides static support libraries that you can add to your Android application, which enables you to use APIs that are either not available on older platform versions or use utility APIs that are not part of the framework APIs.

Update URLs for servers and services

If your application accesses remote servers or services, make sure you are using the production URL or path for the server or service and not a test URL or path.

Implement Licensing (if you are releasing on Google Play)

If you are releasing a paid application through Google Play, consider adding support for Google Play Licensing. Licensing lets you control access to your application based on whether the current user has purchased it. Using Google Play Licensing is optional even if you are releasing your app through Google Play.

For more information about Google Play Licensing Service and how to use it in your application, see Application Licensing.

Building Your Application for Release


After you finish configuring your application you can build it into a release-ready .apk fle that is signed and optimized. The JDK includes the tools for signing the .apk file (Keytool and Jarsigner); the Android SDK includes the tools for compiling and optimizing the .apk file. If you are using Eclipse with the ADT plugin or you are using the Ant build script from the command line, you can automate the entire build process.

Building with Eclipse

You can use the Eclipse Export Wizard to build a release-ready .apk file that is signed with your private key and optimized. To learn how to run the Export Wizard, see Compile and sign with Eclipse ADT. The Export Wizard compiles your application for release, signs your application with your private key, and optimizes your application with the zipalign tool. The Export Wizard should run successfully if you have run or debugged your application from Eclipse and you have no errors in your application (see Building and Running from Eclipse with ADT for more information.

The Export Wizard assumes that you have a certificate and private key suitable for signing your application. If you do not have a suitable certificate and private key, the Export Wizard will help you generate one (see Signing Your Applicationsfor more information about the signing process and signing guidelines.

Building with Ant

You can use the Ant build script (included in the Android SDK) to build a release-ready .apk file that is signed with your private key and optimized. To learn how to do this, see Building in Release Mode. This build method assumes you have acertificate and private key suitable for signing your application. If you do not have a suitable certificate and private key, the Export Wizard will help you generate one (see Signing Your Applications for more information about the signing process and signing guidelines.

Preparing External Servers and Resources


If your application relies on a remote server, make sure the server is secure and that it is configured for production use. This is particularly important if you are implementing in-app billing in your application and you are performing the signature verification step on a remote server.

Also, if your application fetches content from a remote server or a real-time service (such as a content feed), be sure the content you are providing is up to date and production-ready.

Testing Your Application for Release


Testing the release version of your application helps ensure that your application runs properly under realistic device and network conditions. Ideally, you should test your application on at least one handset-sized device and one tablet-sized device to verify that your user interface elements are sized correctly and that your application's performance and battery efficiency are acceptable.

As a starting point for testing, see What to Test. This article provides a summary of common Android situations that you should consider when you are testing. When you are done testing and you are satisfied that the release version of your application behaves correctly, you can release your application to users. For more information, see Releasing Your Application to Users. If you are publishing your application on Google Play, see Launch Checklist for Google Play.

Versioning Your Applications

QUICKVIEW

  • Your application must be versioned
  • You set the version in the application's manifest file
  • How you version your applications affects how users upgrade
  • Determine your versioning strategy early in the development process, including considerations for future releases.

IN THIS DOCUMENT

  1. Setting Application Version
  2. Specifying Your Application's System API Requirements

SEE ALSO

  1. Preparing to Publish Your Application
  2. Launch Checklist for Google Play
  3. The AndroidManifest.xml File

Versioning is a critical component of your application upgrade and maintenance strategy. Versioning is important because:

  • Users need to have specific information about the application version that is installed on their devices and the upgrade versions available for installation.
  • Other applications — including other applications that you publish as a suite — need to query the system for your application's version, to determine compatibility and identify dependencies.
  • Services through which you will publish your application(s) may also need to query your application for its version, so that they can display the version to users. A publishing service may also need to check the application version to determine compatibility and establish upgrade/downgrade relationships.

The Android system does not use app version information to enforce restrictions on upgrades, downgrades, or compatibility of third-party apps. Instead, you (the developer) are responsible for enforcing version restrictions within your application or by informing users of the version restrictions and limitations. The Android system does, however, enforce system version compatibility as expressed by the minSdkVersion attribute in the manifest. This attribute allows an application to specify the minimum system API with which it is compatible. For more information see Specifying Minimum System API Version.

Setting Application Version


To define the version information for your application, you set attributes in the application's manifest file. Two attributes are available, and you should always define values for both of them:

  • android:versionCode — An integer value that represents the version of the application code, relative to other versions.

    The value is an integer so that other applications can programmatically evaluate it, for example to check an upgrade or downgrade relationship. You can set the value to any integer you want, however you should make sure that each successive release of your application uses a greater value. The system does not enforce this behavior, but increasing the value with successive releases is normative.

    Typically, you would release the first version of your application with versionCode set to 1, then monotonically increase the value with each release, regardless whether the release constitutes a major or minor release. This means that the android:versionCode value does not necessarily have a strong resemblance to the application release version that is visible to the user (see android:versionName, below). Applications and publishing services should not display this version value to users.

  • android:versionName — A string value that represents the release version of the application code, as it should be shown to users.

    The value is a string so that you can describe the application version as a <major>.<minor>.<point> string, or as any other type of absolute or relative version identifier.

    As with android:versionCode, the system does not use this value for any internal purpose, other than to enable applications to display it to users. Publishing services may also extract the android:versionName value for display to users.

You define both of these version attributes in the <manifest> element of the manifest file.

Here's an example manifest that shows the android:versionCode and android:versionName attributes in the <manifest>element.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.package.name"
      android:versionCode="2"
      android:versionName="1.1">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        ...
    </application>
</manifest>

In this example, note that android:versionCode value indicates that the current .apk contains the second release of the application code, which corresponds to a minor follow-on release, as shown by the android:versionName string.

The Android framework provides an API to let applications query the system for version information about your application. To obtain version information, applications use the getPackageInfo(java.lang.String, int) method ofPackageManager.

Specifying Your Application's System API Requirements


If your application requires a specific minimum version of the Android platform, or is designed only to support a certain range of Android platform versions, you can specify those version requirements as API Level identifiers in the application's manifest file. Doing so ensures that your application can only be installed on devices that are running a compatible version of the Android system.

To specify API Level requirements, add a <uses-sdk> element in the application's manifest, with one or more of these attributes:

  • android:minSdkVersion — The minimum version of the Android platform on which the application will run, specified by the platform's API Level identifier.
  • android:targetSdkVersion — Specifies the API Level on which the application is designed to run. In some cases, this allows the application to use manifest elements or behaviors defined in the target API Level, rather than being restricted to using only those defined for the minimum API Level.
  • android:maxSdkVersion — The maximum version of the Android platform on which the application is designed to run, specified by the platform's API Level identifier. Important: Please read the <uses-sdk> documentation before using this attribute.

When preparing to install your application, the system checks the value of this attribute and compares it to the system version. If the android:minSdkVersion value is greater than the system version, the system aborts the installation of the application. Similarly, the system installs your application only if its android:maxSdkVersion is compatible with the platform version.

If you do not specify these attributes in your manifest, the system assumes that your application is compatible with all platform versions, with no maximum API Level.

To specify a minimum platform version for your application, add a <uses-sdk> element as a child of <manifest>, then define the android:minSdkVersion as an attribute.

For more information, see the <uses-sdk> manifest element documentation and the API Levels document.

Signing Your Applications

QUICKVIEW

  • All Android apps must be signed
  • You can sign with a self-signed key
  • How you sign your apps is critical — read this document carefully
  • Determine your signing strategy early in the development process

IN THIS DOCUMENT

  1. Signing Process
  2. Signing Strategies
  3. Basic Setup for Signing
  4. Signing in Debug Mode
  5. Signing Release Mode
    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
    5. Compile and sign with Eclipse ADT
  6. Securing Your Private Key

SEE ALSO

  1. Versioning Your Applications
  2. Preparing to Publish

The Android system requires that all installed applications be digitally signed with a certificate whose private key is held by the application's developer. The Android system uses the certificate as a means of identifying the author of an application and establishing trust relationships between applications. The certificate is not used to control which applications the user can install. The certificate does not need to be signed by a certificate authority: it is perfectly allowable, and typical, for Android applications to use self-signed certificates.

The important points to understand about signing Android applications are:

  • All applications must be signed. The system will not install an application on an emulator or a device if it is not signed.
  • To test and debug your application, the build tools sign your application with a special debug key that is created by the Android SDK build tools.
  • When you are ready to release your application for end-users, you must sign it with a suitable private key. You cannot publish an application that is signed with the debug key generated by the SDK tools.
  • You can use self-signed certificates to sign your applications. No certificate authority is needed.
  • The system tests a signer certificate's expiration date only at install time. If an application's signer certificate expires after the application is installed, the application will continue to function normally.
  • You can use standard tools — Keytool and Jarsigner — to generate keys and sign your application .apk files.
  • After you sign your application for release, we recommend that you use thezipalign tool to optimize the final APK package.

The Android system will not install or run an application that is not signed appropriately. This applies wherever the Android system is run, whether on an actual device or on the emulator. For this reason, you must set up signing for your application before you can run it or debug it on an emulator or device.

Signing Process


The Android build process signs your application differently depending on which build mode you use to build your application. There are two build modes: debug mode and release mode. You use debug mode when you are developing and testing your application. You use release mode when you want to build a release version of your application that you can distribute directly to users or publish on an application marketplace such as Google Play.

When you build in debug mode the Android SDK build tools use the Keytool utility (included in the JDK) to create a debug key. Because the SDK build tools created the debug key, they know the debug key's alias and password. Each time you compile your application in debug mode, the build tools use the debug key along with the Jarsigner utility (also included in the JDK) to sign your application's .apk file. Because the alias and password are known to the SDK build tools, the tools don't need to prompt you for the debug key's alias and password each time you compile.

When you build in release mode you use your own private key to sign your application. If you don't have a private key, you can use the Keytool utility to create one for you. When you compile your application in release mode, the build tools use your private key along with the Jarsigner utility to sign your application's .apk file. Because the certificate and private key you use are your own, you must provide the password for the keystore and key alias.

The debug signing process happens automatically when you run or debug your application using Eclipse with the ADT plugin. Debug signing also happens automatically when you use the Ant build script with the debug option. You can automate the release signing process by using the Eclipse Export Wizard or by modifying the Ant build script and building with the release option.

Signing Strategies


Some aspects of application signing may affect how you approach the development of your application, especially if you are planning to release multiple applications.

In general, the recommended strategy for all developers is to sign all of your applications with the same certificate, throughout the expected lifespan of your applications. There are several reasons why you should do so:

  • Application upgrade – As you release updates to your application, you must continue to sign the updates with the same certificate or set of certificates, if you want users to be able to upgrade seamlessly to the new version. When the system is installing an update to an application, it compares the certificate(s) in the new version with those in the existing version. If the certificates match exactly, including both the certificate data and order, then the system allows the update. If you sign the new version without using matching certificates, you must also assign a different package name to the application — in this case, the user installs the new version as a completely new application.
  • Application modularity – The Android system allows applications that are signed by the same certificate to run in the same process, if the applications so requests, so that the system treats them as a single application. In this way you can deploy your application in modules, and users can update each of the modules independently if needed.
  • Code/data sharing through permissions – The Android system provides signature-based permissions enforcement, so that an application can expose functionality to another application that is signed with a specified certificate. By signing multiple applications with the same certificate and using signature-based permissions checks, your applications can share code and data in a secure manner.

Another important consideration in determining your signing strategy is how to set the validity period of the key that you will use to sign your applications.

  • If you plan to support upgrades for a single application, you should ensure that your key has a validity period that exceeds the expected lifespan of that application. A validity period of 25 years or more is recommended. When your key's validity period expires, users will no longer be able to seamlessly upgrade to new versions of your application.
  • If you will sign multiple distinct applications with the same key, you should ensure that your key's validity period exceeds the expected lifespan of all versions of all of the applications, including dependent applications that may be added to the suite in the future.
  • If you plan to publish your application(s) on Google Play, the key you use to sign the application(s) must have a validity period ending after 22 October 2033. Google Play enforces this requirement to ensure that users can seamlessly upgrade applications when new versions are available.

As you design your application, keep these points in mind and make sure to use a suitable certificate to sign your applications.

Basic Setup for Signing


Before you begin, make sure that the Keytool utility and Jarsigner utility are available to the SDK build tools. Both of these tools are available in the JDK. In most cases, you can tell the SDK build tools how to find these utilities by setting your JAVA_HOME environment variable so it references a suitable JDK. Alternatively, you can add the JDK version of Keytool and Jarsigner to your PATH variable.

If you are developing on a version of Linux that originally came with GNU Compiler for Java, make sure that the system is using the JDK version of Keytool, rather than the gcj version. If Keytool is already in your PATH, it might be pointing to a symlink at /usr/bin/keytool. In this case, check the symlink target to be sure it points to the Keytool in the JDK.

Signing in Debug Mode


The Android build tools provide a debug signing mode that makes it easier for you to develop and debug your application, while still meeting the Android system requirement for signing your APK. When using debug mode to build your app, the SDK tools invoke Keytool to automatically create a debug keystore and key. This debug key is then used to automatically sign the APK, so you do not need to sign the package with your own key.

The SDK tools create the debug keystore/key with predetermined names/passwords:

  • Keystore name: "debug.keystore"
  • Keystore password: "android"
  • Key alias: "androiddebugkey"
  • Key password: "android"
  • CN: "CN=Android Debug,O=Android,C=US"

If necessary, you can change the location/name of the debug keystore/key or supply a custom debug keystore/key to use. However, any custom debug keystore/key must use the same keystore/key names and passwords as the default debug key (as described above). (To do so in Eclipse/ADT, go to Windows > Preferences > Android > Build.)

Caution: You cannot release your application to the public when signed with the debug certificate.

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.


/** * NOTE: This file has been copied and slightly modified from {com.alibaba.csp.sentinel.datasource.redis}. * <p> * <h2>Redis Datasource Task Elements Operation</h2> * * This class is a concrete implementation of a remote configuration data source, * built on top of Redis's high-performance read/write capabilities and Pub/Sub real-time * messaging mechanism. It enables dynamic loading, listening, and publishing of rule or * configuration data with low latency and strong consistency. * * <p>The primary design objectives are:</p> * * <ul> * <li><b>Real-time Updates</b>: Subscribes to a designated Redis Pub/Sub channel to detect * configuration changes immediately and trigger hot-reload events.</li> * <li><b>Deployment Flexibility</b>: Supports multiple Redis deployment modes including * standalone, Sentinel (for high availability), and Redis Cluster (for horizontal scaling).</li> * <li><b>Security Support</b>: Provides full SSL/TLS encryption support with compatibility for * both JKS and PEM certificate formats, meeting production security requirements.</li> * <li><b>Extensibility</b>: Extends {@link RemoteDatasourceTaskElementsOperation}, adhering to a unified * datasource abstraction contract. Can be seamlessly integrated into systems requiring * runtime reconfiguration, such as rule engines, policy managers, or distributed gateways.</li> * </ul> * * <h3>Working Principle</h3> * <p>During initialization, the class automatically selects the appropriate client based on * the provided {@link RedisConnectionConfig}: * <ul> * <li>If cluster nodes are configured, it creates a {@link RedisClusterClient}.</li> * <li>Otherwise, it uses a {@link RedisClient} for standalone or Sentinel mode connections.</li> * </ul> * * Additionally, it sets up a "lazy-loaded" subscription via {@link #setLazyListener(java.util.function.Supplier)} — * meaning the actual Pub/Sub connection and subscription occur only when an external system * explicitly requests listening (e.g., during startup of a configuration watcher). * This lazy initialization strategy reduces resource consumption and improves application startup time. * * <h3>Key Method Overview</h3> * <table border="1" cell-padding="8"> * <tr><th>Method</th><th>Purpose</th></tr> * <tr> * <td>{@link #getRemoteConfigInfo()}</td> * <td>Retrieves the current configuration value associated with {@code ruleKey} from Redis (via GET)</td> * </tr> * <tr> * <td>{@link #publishConfig(String)}</td> * <td>Publishes new configuration data to Redis (via SET), typically used to broadcast updates</td> * </tr> * <tr> * <td>{@link #subscribeFromChannel(String)}</td> * <td>Establishes a Pub/Sub connection and subscribes to a specific channel; incoming messages * are dispatched through {@link DelegatingRedisPubSubListener}</td> * </tr> * <tr> * <td>{@link #close()}</td> * <td>Gracefully shuts down the Redis client and releases all underlying resources</td> * </tr> * </table> * * <h3>Typical Use Cases</h3> * <ul> * <li>Dynamic rule loading in rule engines (e.g., Drools, Easy Rules)</li> * <li>Hot-reloading of distributed configurations in microservices</li> * <li>Real-time policy or permission updates in access control systems</li> * <li>Centralized rate-limiting or circuit-breaker configuration management</li> * </ul> * <h3>Example Usage</h3> * <pre>{@code * RedisConnectionConfig config = new RedisConnectionConfig(); * config.setHost("localhost"); * config.setPort(6379); * config.setTimeout(5000); * * RedisDatasourceTaskElementsOperation redisSource = * new RedisDatasourceTaskElementsOperation(config, "rule:flow", "channel:rule-update", ConfigFormat.JSON); * * // Retrieve current configuration * String currentConfig = redisSource.getRemoteConfigInfo(); * * // Start listening (triggers lazy subscription) * redisSource.startListen(); * * // Publish new config (other instances will receive notification) * redisSource.publishConfig("{\"rateLimit\": 1000}"); * * // Clean up resources * redisSource.close(); * }</pre> * * @author <a href="mailto:929160069@qq.com">zhangpengfei</a> * @since 3.0.2 */ 编译报错 [ERROR] /Users/zhangpengfei/workspace/assembly/assembly-simplified-cron/cron-redis-datasource-driven-scheduled/src/main/java/top/osjf/cron/datasource/driven/scheduled/redis/RedisDatasourceTaskElementsOperation.java:97: 错误: 此处不允许使用标记: <tr> [ERROR] * <tr>
最新发布
11-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值