From 4143781cdea0741ce6e87967c4ab903288c3e4c3 Mon Sep 17 00:00:00 2001 From: Scott Main Date: Thu, 7 Jul 2011 14:51:56 -0700 Subject: docs: add docs for market OBB includes splitting the Licensing dev guide into multiple pages; Turned original licensing doc into a redirect to the new files that are under guide/market/licensing/; Fix all links pointing to app licensing Change-Id: Ic49493f0e560db225dd7a382ffabc904a2fa1228 --- docs/html/guide/appendix/install-location.jd | 2 +- docs/html/guide/developing/tools/proguard.jd | 2 +- docs/html/guide/guide_toc.cs | 22 +- docs/html/guide/market/expansion-files.jd | 1259 +++++++++++ .../guide/market/licensing/adding-licensing.jd | 1072 +++++++++ docs/html/guide/market/licensing/index.jd | 61 + .../guide/market/licensing/licensing-reference.jd | 439 ++++ docs/html/guide/market/licensing/overview.jd | 245 ++ docs/html/guide/market/licensing/setting-up.jd | 707 ++++++ docs/html/guide/publishing/licensing.html | 11 + docs/html/guide/publishing/licensing.jd | 2388 -------------------- docs/html/guide/publishing/preparing.jd | 3 +- docs/html/guide/publishing/publishing.jd | 4 +- docs/html/guide/publishing/publishing_overview.jd | 3 +- .../html/guide/topics/manifest/manifest-element.jd | 2 +- docs/html/sitemap.txt | 2 +- 16 files changed, 3825 insertions(+), 2397 deletions(-) create mode 100644 docs/html/guide/market/expansion-files.jd create mode 100644 docs/html/guide/market/licensing/adding-licensing.jd create mode 100644 docs/html/guide/market/licensing/index.jd create mode 100644 docs/html/guide/market/licensing/licensing-reference.jd create mode 100644 docs/html/guide/market/licensing/overview.jd create mode 100644 docs/html/guide/market/licensing/setting-up.jd create mode 100644 docs/html/guide/publishing/licensing.html delete mode 100644 docs/html/guide/publishing/licensing.jd diff --git a/docs/html/guide/appendix/install-location.jd b/docs/html/guide/appendix/install-location.jd index 292d3e75d997..e5ed226322d5 100644 --- a/docs/html/guide/appendix/install-location.jd +++ b/docs/html/guide/appendix/install-location.jd @@ -174,7 +174,7 @@ external storage, it can never receive this broadcast.
Copy Protection
Your application cannot be installed to a device's SD card if it uses Android Market's Copy Protection feature. However, if you use Android Market's - Application Licensing instead, your + Application Licensing instead, your application can be installed to internal or external storage, including SD cards.
diff --git a/docs/html/guide/developing/tools/proguard.jd b/docs/html/guide/developing/tools/proguard.jd index eca262a3ba08..ea8a1eabafda 100644 --- a/docs/html/guide/developing/tools/proguard.jd +++ b/docs/html/guide/developing/tools/proguard.jd @@ -39,7 +39,7 @@ parent.link=index.html sized .apk file that is more difficult to reverse engineer. Because ProGuard makes your application harder to reverse engineer, it is important that you use it when your application utilizes features that are sensitive to security like when you are - Licensing Your Applications.

+ Licensing Your Applications.

ProGuard is integrated into the Android build system, so you do not have to invoke it manually. ProGuard runs only when you build your application in release mode, so you do not diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs index 4a9a6848632a..fd2ec93c0d87 100644 --- a/docs/html/guide/guide_toc.cs +++ b/docs/html/guide/guide_toc.cs @@ -451,8 +451,24 @@

  • Publishing on Android Market
  • -
  • +
  • +
    Application Licensing +
    +
  • @@ -485,6 +501,10 @@
  • Multiple APK Support
  • +
  • + APK Expansion Files + new! +
  • diff --git a/docs/html/guide/market/expansion-files.jd b/docs/html/guide/market/expansion-files.jd new file mode 100644 index 000000000000..09f1d2e09067 --- /dev/null +++ b/docs/html/guide/market/expansion-files.jd @@ -0,0 +1,1259 @@ +page.title=APK Expansion Files +@jd:body + + +
    +
    +

    Quickview

    +
      +
    • Recommended for most apps that exceed the 50MB APK limit
    • +
    • You can provide up to 4GB of additional data for each APK
    • +
    • Android Market hosts and serves the expansion files at no charge
    • +
    • The files can be any file type you want and are saved to the device's shared storage
    • +
    + +

    In this document

    +
      +
    1. Overview +
        +
      1. File name format
      2. +
      3. Storage location
      4. +
      5. Download process
      6. +
      7. Development checklist
      8. +
      +
    2. +
    3. Rules and Limitations
    4. +
    5. Downloading the Expansion Files +
        +
      1. About the Expansion Downloader Library
      2. +
      3. Preparing to use the Expansion Downloader Library
      4. +
      5. Declaring user permissions
      6. +
      7. Implementing the downloader service
      8. +
      9. Implementing the alarm receiver
      10. +
      11. Starting the download
      12. +
      13. Receiving download progress
      14. +
      +
    6. +
    7. Using APKExpansionPolicy
    8. +
    9. Reading the Expansion File +
        +
      1. Getting the file names
      2. +
      3. Using the APK Expansion Zip Library
      4. +
      +
    10. +
    11. Testing Your Expansion Files +
        +
      1. Testing file reads
      2. +
      3. Testing file downloads
      4. +
      +
    12. +
    13. Updating Your Application
    14. +
    + +

    See also

    +
      +
    1. Application Licensing
    2. +
    3. Multiple +APK Support
    4. +
    +
    +
    + + + +

    Android Market currently requires that your APK file be no more than 50MB. For most +applications, this is plenty of space for all the application's code and assets. +However, some apps need more space for high-fidelity graphics, media files, or other large assets. +Previously, if your app exceeded 50MB, you had to host and download the additional resources +yourself when the user opens the app. Hosting and serving the extra files can be costly, and the +user experience is often less than ideal. To make this process easier for you and more pleasant +for users, Android Market allows you to attach two large expansion files that supplement your +APK.

    + +

    Android Market hosts the expansion files for your application and serves them to the device at +no cost to you. The expansion files are saved to the device's shared storage location (the +SD card or USB-mountable partition; also known as the "external" storage) where your app can access +them. On most devices, Android Market downloads the expansion file(s) at the same time it +downloads the APK, so your application has everything it needs when the user opens it for the +first time. In some cases, however, your application must download the files from Android Market +when your application starts.

    + + + +

    Overview

    + +

    Each time you upload an APK using the Android Market Developer Console, you have the option to +add one or two expansion files to the APK. Each file can be up to 2GB and it can be any format you +choose, but we recommend you use a compressed file to conserve bandwidth during the download. +Conceptually, each expansion file plays a different role:

    + + + +

    Note: The patch expansion file is semantically the same as the +main expansion file—you can use each file any way you want. The system does +not use the patch expansion file to perform patching for your app. You must perform patching +yourself or be able to distinguish between the two files.

    + + + +

    File name format

    + +

    Each expansion file you upload can be any format you choose (ZIP, PDF, MP4, etc.). Regardless of +the file type, Android Market considers them opaque binary blobs and renames the files +using the following scheme:

    + +
    +[main|patch].<expansion-version>.<package-name>.obb
    +
    + +

    There are three components to this scheme:

    + +
    +
    {@code main} or {@code patch}
    +
    Specifies whether the file is the main or patch expansion file. There can be +only one main file and one patch file for each APK.
    +
    {@code <expansion-version>}
    +
    This is an integer that matches the version code of the APK with which the expansion is +first associated (it matches the application's {@code android:versionCode} +value). +

    "First" is emphasized because although the Android Market Developer Console allows you to +re-use an uploaded expansion file with a new APK, the expansion file's name does not change—it +retains the version applied to it when you first uploaded the file.

    +
    {@code <package-name>}
    +
    Your application's Java-style package name.
    +
    + +

    For example, suppose your APK version is 314159 and your package name is com.example.app. If you +upload a main expansion file, the file is renamed to:

    +
    main.314159.com.example.app.obb
    + + +

    Storage location

    + +

    When Android Market downloads your expansion files to a device, it saves them to the system's +shared storage location. To ensure proper behavior, you must not delete, move, or rename the +expansion files. In the event that your application must perform the download from Android Market +itself, you must save the files to the exact same location.

    + +

    The specific location for your expansion files is:

    + +
    +<shared-storage>/Android/obb/<package-name>/
    +
    + + +

    + +

    Note: The location of the shared storage may be +different on different devices, so you should never refer to the shared storage space using an +absolute URI path. Always use {@link android.os.Environment#getExternalStorageDirectory} to +retrieve the root directory of the shared storage location.

    + +

    For each application, there are never more than two expansion files in this directory. +One is the main expansion file and the other is the patch expansion file (if necessary). Previous +versions are overwritten when you update your application with new expansion files.

    + +

    If you must unpack the contents of your expansion files, do not delete the +{@code .obb} expansion files afterwards and do not save the unpacked data +in the same directory. You should save your unpacked files in the directory +specified by {@link android.content.Context#getExternalFilesDir getExternalFilesDir()}. However, +if possible, it's best if you use an expansion file format that allows you to read directly from +the file instead of requiring you to unpack the data. For example, we've provided a library +project called the APK Expansion Zip Library that reads your data directly +from the ZIP file.

    + +

    Note: If you're packaging media files into a ZIP, you can use media +playback calls on the files with offset and length controls (such as {@link +android.media.MediaPlayer#setDataSource(FileDescriptor,long,long) MediaPlayer.setDataSource()} and +{@link android.media.SoundPool#load(FileDescriptor,long,long,int) SoundPool.load()}) without the +need to unpack your ZIP. In order for this to work, you must not perform additional compression on +the media files when creating the ZIP packages. For example, when using the zip tool, +you should use the -n option to specify the file suffixes that should not be +compressed:
    +zip -n .mp4;.ogg main_expansion media_files

    + + +

    Download process

    + +

    Most of the time, Android Market downloads and saves your expansion files at the same time it +downloads the APK to the device. However, in some cases Android Market +cannot download the expansion files or the user might have deleted previously downloaded expansion +files. To handle these situations, your app must be able to download the files +itself when the main activity starts, using a URL provided by Android Market.

    + +

    The download process from a high level looks like this:

    + +
      +
    1. User selects to install your app from Android Market.
    2. +
    3. If Android Market is able to download the expansion files (which is the case for most +devices), it downloads them along with the APK. +

      If Android Market is unable to download the expansion files, it downloads the +APK only.

      +
    4. +
    5. When the user launches your application, your app must check whether the expansion files are +already saved on the device. +
        +
      1. If yes, your app is ready to go.
      2. +
      3. If no, your app must download the expansion files over HTTP from Android Market. Your app +must send a request to the Android Market client using the Android Market's Application Licensing service, which +responds with the name, file size, and URL for each expansion file. With this information, you then +download the files and save them to the proper storage location.
      4. +
      +
    6. +
    + +

    Caution: It is critical that you include the necessary code to +download the expansion files from Android Market in the event that the files are not already on the +device when your application starts. As discussed in the following section about Downloading the Expansion Files, we've made a library available to you that +greatly simplifies this process and performs the download from a service with a minimal amount of +code from you.

    + + + + +

    Development checklist

    + +

    Here's a summary of the tasks you should perform to use expansion files with your +application:

    + +
      +
    1. First determine whether your application absolutely requires more than 50MB per installation. +Space is precious and you should keep your total application size as small as possible. If your app +uses more than 50MB in order to provide multiple versions of your graphic assets for multiple screen +densities, consider instead publishing multiple APKs in which each APK +contains only the assets required for the screens that it targets.
    2. +
    3. Determine which application resources to separate from your APK and package them in a +file to use as the main expansion file. +

      Normally, you should only use the second patch expansion file when performing updates to +the main expansion file. However, if your resources exceed the 2GB limit for the main +expansion file, you can use the patch file for the rest of your assets.

      +
    4. +
    5. Develop your application such that it uses the resources from your expansion files in the +device's shared storage location. +

      Remember that you must not delete, move, or rename the expansion files.

      +

      If your application doesn't demand a specific format, we suggest you create ZIP files for +your expansion files, then read them using the APK Expansion Zip +Library.

      +
    6. +
    7. Add logic to your application's main activity that checks whether the expansion files +are on the device upon start-up. If the files are not on the device, use Android Market's Application Licensing service to request URLs +for the expansion files, then download and save them. +

      To greatly reduce the amount of code you must write and ensure a good user experience +during the download, we recommend you use the Expansion Downloader +Library to implement your download behavior.

      +

      If you build your own download service instead of using the library, be aware that you +must not change the name of the expansion files and must save them to the proper +storage location.

    8. +
    + +

    Once you've finished your application development, follow the guide to Testing +Your Expansion Files.

    + + + + + + +

    Rules and Limitations

    + +

    Adding APK expansion files is a feature available when you upload your application using the +Android Market Developer Console. When uploading your application for the first time or updating an +application that uses expansion files, you must be aware of the following rules and limitations:

    + +
      +
    1. Each expansion file can be no more than 2GB.
    2. +
    3. In order to download your expansion files from Android Market, the user must have +acquired your application from Android Market. Android Market will not +provide the URLs for your expansion files if the application was installed by other means.
    4. +
    5. When performing the download from within your application, the URL that Android Market +provides for each file is unique for every download and each one expires shortly after it is given +to your application.
    6. +
    7. If you update your application with a new APK or upload multiple APKs for the same +application, you can select expansion files that you've uploaded for a previous APK. The +expansion file's name does not change—it retains the version received by the APK to +which the file was originally associated.
    8. +
    9. If you use expansion files in combination with multiple APKs in order to +provide different expansion files for different devices, you still must upload separate APKs +for each device in order to provide a unique {@code versionCode} +value and declare different filters for +each APK.
    10. +
    11. You cannot issue an update to your application by changing the expansion files +alone—you must upload a new APK to update your app. If your changes only +concern the assets in your expansion files, you can update your APK simply by changing the {@code versionCode} (and +perhaps also the {@code +versionName}).

    12. +
    13. Do not save other data into your obb/ +directory. If you must unpack some data, save it into the location specified by {@link +android.content.Context#getExternalFilesDir getExternalFilesDir()}.
    14. +
    15. Do not delete or rename the {@code .obb} expansion file (unless you're +performing an update). Doing so will cause Android Market (or your app itself) to repeatedly +download the expansion file.
    16. +
    17. When updating an expansion file manually, you must delete the previous expansion file.
    18. +
    + + + + + + + + + +

    Downloading the Expansion Files

    + +

    In most cases, Android Market downloads and saves your expansion files to the device at the same +time it installs or updates the APK. This way, the expansion files are available when your +application launches for the first time. However, in some cases your app must download the +expansion files itself by requesting them from a URL provided to you in a response +from Android Market's Application Licensing service.

    + +

    The basic logic you need to download your expansion files is the following:

    + +
      +
    1. When your application starts, look for the expansion files on the shared storage location (in the +Android/obb/<package-name>/ directory). +
        +
      1. If the expansion files are there, you're all set and your application can continue.
      2. +
      3. If the expansion files are not there: +
          +
        1. Perform a request using the License Verification Library to get your +app's expansion file names, sizes, and URLs.
        2. +
        3. Use the URLs provided by Android Market to download the expansion files and save +the expansion files. You must save the files to the shared storage location +(Android/obb/<package-name>/) and use the exact file name provided +by Android Market's response. +

          Note: The URL that Android Market provides for your +expansion files is unique for every download and each one expires shortly after it is given to +your application.

          +
        4. +
        +
      4. +
      +
    2. +
    + + +

    If your application is free (not a paid app), then you probably haven't used the Application Licensing service. It's primarily +designed for you to enforce +licensing policies for your application and ensure that the user has the right to +use your app (he or she rightfully paid for it on Android Market). In order to facilitate the +expansion file functionality, the licensing service has been enhanced to provide a response +to your application that includes the URL of your application's expansion files that are hosted +on Android Market. So, even if your application is free for users, you need to include the Android +Market License Verification Library (LVL) to use APK expansion files. Of course, if your application +is free, you don't need to enforce license verification—you simply need the +library to perform the request that returns the URL of your expansion files.

    + +

    Note: Whether your application is free or not, Android Market +returns the expansion file URLs only if the user acquired your application from Android Market.

    + +

    To simplify this work for you, we've built the Expansion Downloader +Library, which requests the expansion file URLs through the licensing service and +downloads the expansion files for you. By adding this library and a few code hooks to your +application, almost all the work to download the expansion files is already coded for you, including +a status notification that tracks the download progress. As such, in order to provide the best user +experience with minimal effort on your behalf, we recommend you use the +Expansion Downloader Library to download your expansion files. The information in the following +sections explain how to integrate the library into your application.

    + +

    If you'd rather develop your own solution to download the expansion files using the Android +Market URLs, you must follow the Application +Licensing documentation to perform a license request, then retrieve the expansion file names, +sizes, and URLs from the response extras. You should use the {@code +APKExpansionPolicy} class (included in the License Verification Library) as your licensing +policy, which captures the expansion file names, sizes, and URLs from the licensing service..

    + + + +

    About the Expansion Downloader Library

    + +

    To use APK expansion files with your application and provide the best user experience with +minimal effort on your behalf, we recommend you use the Android Market Expansion Downloader +Library.

    + +

    As mentioned above, in order to use expansion files hosted by Android Market, you must use +the Android Market License Verification Library (LVL) to request the URLs from which to download the +expansion files. In addition to the LVL, you need a set of code that downloads the expansion files +over an HTTP connection and saves them to the proper location on the device's shared storage. +As you build this procedure into your application, there are several issues you should take into +consideration:

    + + + +

    Fortunately, the Android Market Expansion Downloader Library handles all of this work for you +and also allows your app to pause and resume the download. To implement expansion file downloads +using the library, all you need to do is:

    + + + + + +

    Preparing to use the Expansion Downloader Library

    + +

    To use the Expansion Downloader Library, you need to +download two packages from the SDK Manager and add the appropriate libraries to your +application.

    + +

    First, open the Android SDK Manager, expand Extras and download:

    + + +

    If you're using Eclipse, create a project for each library and add it to your app:

    +
      +
    1. Create a new Library Project for the License Verification Library and Expansion Downloader +Library. For each library: +
        +
      1. Begin a new Android project.
      2. +
      3. Select Create project from existing +source and choose the library from the {@code <sdk>/extras/google/} directory.
      4. +
      5. Specify a Project Name such as "Android Market License Library" and "Market +Downloader +Library"
      6. +
      7. Click Finish.
      8. +
      +

      Note: The Expansion Downloader Library depends on the License +Verification Library. Be sure to add the License +Verification Library to the Expansion Downloader Library's project properties (same process as +steps 2 and 3 below).

      +
    2. +
    3. Right-click the Android project in which you want to use APK expansion files and +select Properties.
    4. +
    5. In the Library panel, click Add to select and add each of the +libraries to your application.
    6. +
    + +

    Or, from a command line, update your project to include the libraries:

    +
      +
    1. Change directories to the <sdk>/tools/ directory.
    2. +
    3. Execute android update project with the {@code --library} option to add both the +LVL and the Downloader Library to your project. For example: +
      +android update project --path ~/Android/MyApp \
      +--library ~/android_sdk/extras/google/market_licensing \
      +--library ~/android_sdk/extras/google/market_downloader
      +
      +
    4. +
    + +

    With both the License Verification Library and Expansion Downloader Library added to your +application, you'll be able to quickly integrate the ability to download expansion files from +Android Market. The format that you choose for the expansion files and how you read them +from the shared storage is a separate implementation that you should consider based on your +application needs.

    + +

    Tip: The Expansion Downloader package includes a sample application +that shows how to use the Expansion Downloader library in an app. The sample uses a third library +available in the Expansion Downloader package called the APK Expansion Zip Library. If you plan on +using ZIP files for your expansion files, we suggest you also add the APK Expansion Zip Library to +your application. You might want to use the sample application as a starting point for your +implementation.

    + + + +

    Declaring user permissions

    + +

    In order to download the expansion files, the Expansion Downloader Library +requires several permissions that you must declare in your application's manifest file. They +are:

    + +
    +<manifest ...>
    +    <!-- Required to access Android Market Licensing -->
    +    <uses-permission android:name="com.android.vending.CHECK_LICENSE" />
    +
    +    <!-- Required to download files from Android Market -->
    +    <uses-permission android:name="android.permission.INTERNET" />
    +
    +    <!-- Required to keep CPU alive while downloading files (NOT to keep screen awake) -->
    +    <uses-permission android:name="android.permission.WAKE_LOCK" />
    +
    +    <!-- Required to poll the state of the network connection and respond to changes -->
    +    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    +
    +    <!-- Required to check whether Wi-Fi is enabled -->
    +    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    +
    +    <!-- Required to read and write the expansion files on shared storage -->
    +    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    +    ...
    +</manifest>
    +
    + +

    Note: By default, the Expansion Downloader Library requires API +level 4, but the APK Expansion Zip Library requires API level 5.

    + + +

    Implementing the downloader service

    + +

    In order to perform downloads in the background, the Expansion Downloader Library provides its +own {@link android.app.Service} subclass called {@code DownloaderService} that you should extend. In +addition to downloading the expansion files for you, the {@code DownloaderService} also:

    + + + +

    All you need to do is create a class in your application that extends the {@code +DownloaderService} class and override three methods to provide specific application details:

    + +
    +
    {@code getPublicKey()}
    +
    This must return a string that is the Base64-encoded RSA public key for your publisher +account, available from the profile page on the Android Market Developer Console (see Setting Up for Licensing).
    +
    {@code getSALT()}
    +
    This must return an array of random bytes that the licensing {@code Policy} uses to +create an {@code +Obfuscator}. The salt ensures that your obfuscated {@link android.content.SharedPreferences} +file in which your licensing data is saved will be unique and non-discoverable.
    +
    {@code getAlarmReceiverClassName()}
    +
    This must return the class name of the {@link android.content.BroadcastReceiver} in +your application that should receive the alarm indicating that the download should be +restarted (which might happen if the downloader service unexpectedly stops).
    +
    + +

    For example, here's a complete implementation of {@code DownloaderService}:

    + +
    +public class SampleDownloaderService extends DownloaderService {
    +    // You must use the public key belonging to your publisher account
    +    public static final String BASE64_PUBLIC_KEY = "YourAndroidMarketLVLKey";
    +    // You should also modify this salt
    +    public static final byte[] SALT = new byte[] { 1, 42, -12, -1, 54, 98,
    +            -100, -12, 43, 2, -8, -4, 9, 5, -106, -107, -33, 45, -1, 84
    +    };
    +
    +    @Override
    +    public String getPublicKey() {
    +        return BASE64_PUBLIC_KEY;
    +    }
    +
    +    @Override
    +    public byte[] getSALT() {
    +        return SALT;
    +    }
    +
    +    @Override
    +    public String getAlarmReceiverClassName() {
    +        return SampleAlarmReceiver.class.getName();
    +    }
    +}
    +
    + +

    Notice: You must update the {@code BASE64_PUBLIC_KEY} value +to be the public key belonging to your publisher account. You can find the key in the Android +Market Developer Console under your profile information. This is necessary even when testing +your downloads.

    + +

    Remember to declare the service in your manifest file:

    +
    +<application ...>
    +    <service android:name=".SampleDownloaderService" />
    +    ...
    +</application>
    +
    + + + +

    Implementing the alarm receiver

    + +

    In order to monitor the progress of the file downloads and restart the download if necessary, the +{@code DownloaderService} schedules an {@link android.app.AlarmManager#RTC_WAKEUP} alarm that +delivers an {@link android.content.Intent} to a {@link android.content.BroadcastReceiver} in your +application. You must define the {@link android.content.BroadcastReceiver} to call an API +from the Expansion Downloader Library that checks the status of the download and restarts +it if necessary.

    + +

    You simply need to override the {@link android.content.BroadcastReceiver#onReceive +onReceive()} method to call {@code +DownloaderClientMarshaller.startDownloadServiceIfRequired()}.

    + +

    For example:

    + +
    +public class SampleAlarmReceiver extends BroadcastReceiver {
    +    @Override
    +    public void onReceive(Context context, Intent intent) {
    +        try {
    +            DownloaderClientMarshaller.startDownloadServiceIfRequired(context, intent,
    +                    SampleDownloaderService.class);
    +        } catch (NameNotFoundException e) {
    +            e.printStackTrace();
    +        }      
    +    }
    +}
    +
    + +

    Notice that this is the class for which you must return the name +in your service's {@code getAlarmReceiverClassName()} method (see the previous section).

    + +

    Remember to declare the receiver in your manifest file:

    +
    +<application ...>
    +    <receiver android:name=".SampleAlarmReceiver" />
    +    ...
    +</application>
    +
    + + + +

    Starting the download

    + +

    The main activity in your application (the one started by your launcher icon) is +responsible for verifying whether the expansion files are already on the device and initiating +the download if they are not.

    + +

    Starting the download using the Expansion Downloader library requires the following +procedures:

    + +
      +
    1. Check whether the files have been downloaded. +

      The Expansion Downloader library includes some APIs in the {@code Helper} class to +help with this process:

      +
        +
      • {@code getExtendedAPKFileName(Context, c, boolean mainFile, int +versionCode)}
      • +
      • {@code doesFileExist(Context c, String fileName, long fileSize)}
      • +
      +

      For example, the sample app provided in the Expansion Downloader package calls the +following method in the activity's {@link android.app.Activity#onCreate onCreate()} method to check +whether the expansion files already exist on the device:

      +
      +boolean expansionFilesDelivered() {
      +    for (XAPKFile xf : xAPKS) {
      +        String fileName = Helpers.getExpansionAPKFileName(this, xf.mIsBase, xf.mFileVersion);
      +        if (!Helpers.doesFileExist(this, fileName, xf.mFileSize, false))
      +            return false;
      +    }
      +    return true;
      +}        
      +
      +

      In this case, each {@code XAPKFile} object holds the version number and file size of a known +expansion file and a boolean as to whether it's the main expansion file.

      +

      If this method returns false, then the application must begin the download.

      +
    2. +
    3. Start the download by calling the static method {@code +DownloaderClientMarshaller.startDownloadServiceIfRequired(Context c, PendingIntent +notificationClient, Class<?> serviceClass)}. +

      The method takes the following parameters:

      +
        +
      • context: Your application's {@link android.content.Context}.
      • +
      • notificationClient: A {@link android.app.PendingIntent} to start your main +activity. This is used in the {@link android.app.Notification} that the {@code DownloaderService} +creates to show the download progress. When the user selects the notification, the system +invokes the {@link android.app.PendingIntent} you supply here and should open the activity +that shows the download progress (usually the same activity that started the download).
      • +
      • serviceClass: The {@link java.lang.Class} object for your implementation of +{@code DownloaderService}, required to start the service and begin the download if necessary.
      • +
      +

      The method returns an integer that indicates +whether or not the download is required. Possible values are:

      +
        +
      • {@code NO_DOWNLOAD_REQUIRED}: Returned if the files already +exist or a download is already in progress.
      • +
      • {@code LVL_CHECK_REQUIRED}: Returned if a license verification is +required in order to acquire the expansion file URLs.
      • +
      • {@code DOWNLOAD_REQUIRED}: Returned if the expansion file URLs are already known, +but have not been downloaded.
      • +
      +

      The behavior for {@code LVL_CHECK_REQUIRED} and {@code DOWNLOAD_REQUIRED} are essentially the +same and you normally don't need to be concerned about them. In your main activity that calls {@code +startDownloadServiceIfRequired()}, you can simply check whether or not the response is {@code +NO_DOWNLOAD_REQUIRED}. If the response is anything other than {@code NO_DOWNLOAD_REQUIRED}, +the Expansion Downloader library begins the download and you should update your activity UI to +display the download progress (see the next step). If the response is {@code +NO_DOWNLOAD_REQUIRED}, then the files are available and your application can start.

      +

      For example:

      +
      +@Override
      +public void onCreate(Bundle savedInstanceState) {
      +    // Check if expansion files are available before going any further
      +    if (!expansionFilesDelivered()) {
      +        // Build an Intent to start this activity from the Notification
      +        Intent notifierIntent = new Intent(this, MainActivity.getClass());
      +        notifierIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
      +                                Intent.FLAG_ACTIVITY_CLEAR_TOP);
      +        ...
      +        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
      +                notifierIntent, PendingIntent.FLAG_UPDATE_CURRENT);
      +        
      +        // Start the download service (if required)
      +        int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
      +                        pendingIntent, SampleDownloaderService.class);
      +        // If download has started, initialize this activity to show download progress
      +        if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
      +            // This is where you do set up to display the download progress (next step)
      +            ...
      +            return;
      +        } // If the download wasn't necessary, fall through to start the app
      +    }
      +    startApp(); // Expansion files are available, start the app
      +}
      +
      +
    4. +
    5. When the {@code startDownloadServiceIfRequired()} method returns anything other +than {@code NO_DOWNLOAD_REQUIRED}, create an instance of {@code IStub} by +calling {@code DownloaderClientMarshaller.CreateStub(IDownloaderClient client, Class<?> +downloaderService)}. The {@code IStub} provides a binding between your activity to the downloader +service such that your activity receives callbacks about the download progress. +

      In order to instantiate your {@code IStub} by calling {@code CreateStub()}, you must pass it +an implementation of the {@code IDownloaderClient} interface and your {@code DownloaderService} +implementation. The next section about Receiving download progress discusses +the {@code IDownloaderClient} interface, which you should usually implement in your {@link +android.app.Activity} class so you can update the activity UI when the download state changes.

      +

      We recommend that you call {@code +CreateStub()} to instantiate your {@code IStub} during your activity's {@link +android.app.Activity#onCreate onCreate()} method, after {@code startDownloadServiceIfRequired()} +starts the download.

      +

      For example, in the previous code sample for {@link android.app.Activity#onCreate +onCreate()}, you can respond to the {@code startDownloadServiceIfRequired()} result like this:

      +
      +        // Start the download service (if required)
      +        int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
      +                        pendingIntent, SampleDownloaderService.class);
      +        // If download has started, initialize activity to show progress
      +        if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
      +            // Instantiate a member instance of IStub
      +            mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this,
      +                    SampleDownloaderService.class);
      +            // Inflate layout that shows download progress
      +            setContentView(R.layout.downloader_ui);
      +            return;
      +        }
      +
      + +

      After the {@link android.app.Activity#onCreate onCreate()} method returns, your activity +receives a call to {@link android.app.Activity#onResume onResume()}, which is where you should then +call {@code connect()} on the {@code IStub}, passing it your application's {@link +android.content.Context}. Conversely, you should call +{@code disconnect()} in your activity's {@link android.app.Activity#onStop onStop()} callback.

      +
      +@Override
      +protected void onResume() {
      +    if (null != mDownloaderClientStub) {
      +        mDownloaderClientStub.connect(this);
      +    }
      +    super.onResume();
      +}
      +
      +@Override
      +protected void onStop() {
      +    if (null != mDownloaderClientStub) {
      +        mDownloaderClientStub.disconnect(this);
      +    }
      +    super.onStop();
      +}
      +
      +

      Calling {@code connect()} on the {@code IStub} binds your activity to the {@code +DownloaderService} such that your activity receives callbacks regarding changes to the download +state through the {@code IDownloaderClient} interface.

      +
    6. +
    + + + +

    Receiving download progress

    + +

    To receive updates regarding the download progress and to interact with the {@code +DownloaderService}, you must implement the Downloader Library's {@code IDownloaderClient} interface. +Usually, the activity you use to start the download should implement this interface in order to +display the download progress and send requests to the service.

    + +

    The required interface methods for {@code IDownloaderClient} are:

    + +
    +
    {@code onServiceConnected(Messenger m)}
    +
    After you instantiate the {@code IStub} in your activity, you'll receive a call to this +method, which passes a {@link android.os.Messenger} object that's connected with your instance +of {@code DownloaderService}. To send requests to the service, such as to pause and resume +downloads, you must call {@code DownloaderServiceMarshaller.CreateProxy()} to receive the {@code +IDownloaderService} interface connected to the service. +

    A recommended implementation looks like this:

    +
    +private IDownloaderService mRemoteService;
    +...
    +
    +@Override
    +public void onServiceConnected(Messenger m) {
    +    mRemoteService = DownloaderServiceMarshaller.CreateProxy(m);
    +    mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
    +}
    +
    +

    With the {@code IDownloaderService} object initialized, you can send commands to the +downloader service, such as to pause and resume the download ({@code requestPauseDownload()} +and {@code requestContinueDownload()}).

    +
    +
    {@code onDownloadStateChanged(int newState)}
    +
    The download service calls this when a change in download state occurs, such as the +download begins or completes. +

    The newState value will be one of several possible values specified in +by one of the {@code IDownloaderClient} class's {@code STATE_*} constants.

    +

    To provide a useful message to your users, you can request a corresponding string +for each state by calling {@code Helpers.getDownloaderStringResourceIDFromState()}. This +returns the resource ID for one of the strings bundled with the Expansion Downloader +Library. For example, the string "Download paused because you are roaming" corresponds to {@code +STATE_PAUSED_ROAMING}.

    +
    {@code onDownloadProgress(DownloadProgressInfo progress)}
    +
    The download service calls this to deliver a {@code DownloadProgressInfo} object, +which describes various information about the download progress, including estimated time remaining, +current speed, overall progress, and total so you can update the download progress UI.
    +
    +

    Tip: For examples of these callbacks that update the download +progress UI, see the {@code SampleDownloaderActivity} in the sample app provided with the Expansion +Downloader package.

    + +

    Some public methods for the {@code IDownloaderService} interface you might find useful are:

    + +
    +
    {@code requestPauseDownload()}
    +
    Pauses the download.
    +
    {@code requestContinueDownload()}
    +
    Resumes a paused download.
    +
    {@code setDownloadFlags(int flags)}
    +
    Sets user preferences for network types on which its OK to download the files. The +current implementation supports one flag, {@code FLAGS_DOWNLOAD_OVER_CELLULAR}, but you can add +others. By default, this flag is not enabled, so the user must be on Wi-Fi to download +expansion files. You might want to provide a user preference to enable downloads over +the cellular network. In which case, you can call: +
    +mRemoteService.setDownloadFlags(IDownloaderService.FLAGS_DOWNLOAD_OVER_CELLULAR);
    +
    +
    +
    + + + + +

    Using APKExpansionPolicy

    + +

    If you decide to build your own downloader service instead of using the Android Market +Expansion Downloader Library, you should still use the {@code +APKExpansionPolicy} that's provided in the License Verification Library. The {@code +APKExpansionPolicy} class is nearly identical to {@code ServerManagedPolicy} (available in the +Android Market License Verification Library) but includes additional handling for the APK expansion +file response extras.

    + +

    Note: If you do use the Expansion Downloader Library as discussed in the previous section, the +library performs all interaction with the {@code APKExpansionPolicy} so you don't have to use +this class directly.

    + +

    The class includes methods to help you get the necessary information about the available +expansion files:

    + + + +

    For more information about how to use the {@code APKExpansionPolicy} when you're not +using the Expansion Downloader Library, see the documentation for Adding Licensing to Your App, +which explains how to implement a license policy such as this one.

    + + + + + + + +

    Reading the Expansion File

    + +

    Once your APK expansion files are saved on the device, how you read your files +depends on the type of file you've used. As discussed in the overview, your +expansion files can be any kind of file you +want, but are renamed using a particular file name format and are saved to +{@code <shared-storage>/Android/obb/<package-name>/}.

    + +

    Regardless of how you read your files, you should always first check that the external +storage is available for reading. There's a chance that the user has the storage mounted to a +computer over USB or has actually removed the SD card.

    + +

    Note: When your application starts, you should always check whether +the external storage space is available and readable by calling {@link +android.os.Environment#getExternalStorageState()}. This returns one of several possible strings +that represent the state of the external storage. In order for it to be readable by your +application, the return value must be {@link android.os.Environment#MEDIA_MOUNTED}.

    + + +

    Getting the file names

    + +

    As described in the overview, your APK expansion files are saved +using a specific file name format:

    + +
    +[main|patch].<expansion-version>.<package-name>.obb
    +
    + +

    To get the location and names of your expansion files, you should use the +{@link android.os.Environment#getExternalStorageDirectory()} and {@link +android.content.Context#getPackageName()} methods to construct the path to your files.

    + +

    Here's a method you can use in your application to get an array containing the complete path +to both your expansion files:

    + +
    +// The shared path to all app expansion files
    +private final static String EXP_PATH = "/Android/obb/";
    +
    +static String[] getAPKExpansionFiles(Context ctx, int mainVersion, int patchVersion) {
    +    String packageName = ctx.getPackageName();
    +    Vector<String> ret = new Vector<String>();
    +    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    +        // Build the full path to the app's expansion files
    +        File root = Environment.getExternalStorageDirectory();
    +        File expPath = new File(root.toString() + EXP_PATH + packageName);
    +
    +        // Check that expansion file path exists
    +        if (expPath.exists()) {
    +            if ( mainVersion > 0 ) {
    +                String strMainPath = expPath + File.separator + "main." +
    +                        mainVersion + "." + packageName + ".obb";
    +                File main = new File(strMainPath);
    +                if ( main.isFile() ) {
    +                        ret.add(strMainPath);
    +                }
    +            }
    +            if ( patchVersion > 0 ) {
    +                String strPatchPath = expPath + File.separator + "patch." +
    +                        mainVersion + "." + packageName + ".obb";
    +                File main = new File(strPatchPath);
    +                if ( main.isFile() ) {
    +                        ret.add(strPatchPath);
    +                }
    +            }
    +        }
    +    }
    +    String[] retArray = new String[ret.size()];
    +    ret.toArray(retArray);
    +    return retArray;
    +}
    +
    + +

    You can call this method by passing it your application {@link android.content.Context} +and the desired expansion file's version.

    + +

    There are many ways you could determine the expansion file version number. One simple way is to +save the version in a {@link android.content.SharedPreferences} file when the download begins, by +querying the expansion file name with the {@code APKExpansionPolicy} class's {@code +getExpansionFileName(int index)} method. You can then get the version code by reading the {@link +android.content.SharedPreferences} file when you want to access the expansion +file.

    + +

    For more information about reading from the shared storage, see the Data Storage +documentation.

    + + + +

    Using the APK Expansion Zip Library

    + + + +

    The Android Market Expansion Downloader package includes a library called the APK +Expansion Zip Library. This is an optional library that helps you read your expansion +files when they're saved as ZIP files. Using this library allows you to easily read resources from +your ZIP expansion files as a virtual file system.

    + +

    The APK Expansion Zip Library includes the following classes and APIs:

    + +
    +
    {@code APKExpansionSupport}
    +
    Provides some methods to access expansion file names and ZIP files: + +
    +
    {@code getAPKExpansionFiles()}
    +
    The same method shown above that returns the complete file path to both expansion +files.
    +
    {@code getAPKExpansionZipFile(Context ctx, int mainVersion, int +patchVersion)}
    +
    Returns a {@code ZipResourceFile} representing the sum of both the main file and +patch file. That is, if you specify both the mainVersion and the +patchVersion, this returns a {@code ZipResourceFile} that provides read access to +all the data, with the patch file's data merged on top of the main file.
    +
    +
    + +
    {@code ZipResourceFile}
    +
    Represents a ZIP file on the shared storage and performs all the work to provide a virtual +file system based on your ZIP files. You can get an instance using {@code +APKExpansionSupport.getAPKExpansionZipFile()} or with the {@code ZipResourceFile} by passing it the +path to your expansion file. This class includes a variety of useful methods, but you generally +don't need to access most of them. A couple of important methods are: + +
    +
    {@code getInputStream(String assetPath)}
    +
    Provides an {@link java.io.InputStream} to read a file within the ZIP file. The +assetPath must be the path to the desired file, relative to +the root of the ZIP file contents.
    +
    {@code getAssetFileDescriptor(String assetPath)}
    +
    Provides an {@link android.content.res.AssetFileDescriptor} for a file within the +ZIP file. The assetPath must be the path to the desired file, relative to +the root of the ZIP file contents. This is useful for certain Android APIs that require an {@link +android.content.res.AssetFileDescriptor}, such as some {@link android.media.MediaPlayer} APIs.
    +
    +
    + +
    {@code APEZProvider}
    +
    Most applications don't need to use this class. This class defines a {@link +android.content.ContentProvider} that marshals the data from the ZIP files through a content +provider {@link android.net.Uri} in order to provide file access for certain Android APIs that +expect {@link android.net.Uri} access to media files. +

    The sample application available in the +Expansion Downloader package demonstrates a scenario in which this class is useful +to specify a video with {@link android.widget.VideoView#setVideoURI +VideoView.setVideoURI()}. See the sample app's class {@code SampleZipfileProvider} for an +example of how to extend this class to use in your application.

    +
    + +

    Reading from a ZIP file

    + +

    When using the APK Expansion Zip Library, reading a file from your ZIP usually requires the +following:

    + +
    +// Get a ZipResourceFile representing a merger of both the main and patch files
    +ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(appContext,
    +        mainVersion, patchVersion);
    +        
    +// Get an input stream for a known file inside the expansion file ZIPs
    +InputStream fileStream = expansionFile.getInputStream(pathToFileInsideZip);
    +
    + +

    The above code provides access to any file that exists in either your main expansion file or +patch expansion file, by reading from a merged map of all the files from both files. All you +need to provide the {@code getAPKExpansionFile()} method is your application {@code +android.content.Context} and the version number for both the main expansion file and patch +expansion file.

    + +

    If you'd rather read from a specific expansion file, you can use the {@code +ZipResourceFile} constructor with the path to the desired expansion file:

    + +
    +// Get a ZipResourceFile representing a specific expansion file
    +ZipResourceFile expansionFile = new ZipResourceFile(filePathToMyZip);
    +
    +// Get an input stream for a known file inside the expansion file ZIPs
    +InputStream fileStream = expansionFile.getInputStream(pathToFileInsideZip);
    +
    + + + + + +

    Testing Your Expansion Files

    + +

    Before publishing your application, there are two things you should test: Reading the +expansion files and downloading the files.

    + + +

    Testing file reads

    + +

    Before you upload your application to Android Market, you +should test your application's ability to read the files from the shared storage. All you need to do +is add the files to the appropriate location on the device shared storage and launch your +application:

    + +
      +
    1. On your device, create the appropriate directory on the shared storage where Android +Market will save your files. +

      For example, if your package name is {@code com.example.android}, you need to create +the directory {@code Android/obb/com.example.android/} on the shared storage space. (Plug in +your test device to your computer to mount the shared storage and manually create this +directory.)

      +
    2. +
    3. Manually add the expansion files to that directory. Be sure that you rename your files to +match the file name format that Android Market will use. +

      For example, regardless of the file type, the main expansion file for the {@code +com.example.android} application should be {@code main.0300110.com.example.android.obb}. +The version code can be whatever value you want. Just remember:

      +
        +
      • The main expansion file always starts with {@code main} and the patch file starts with +{@code patch}.
      • +
      • The package name always matches that of the APK to which the file is attached on +Android Market. +
      +
    4. +
    5. Now that the expansion file(s) are on the device, you can install and run your application to +test your expansion file(s).
    6. +
    + +

    Here are some reminders about handling the expansion files:

    + + + + +

    Testing file downloads

    + +

    Because your application must sometimes manually download the expansion files when it first +opens, it's important that you test this process to be sure your application can successfully query +for the URLs, download the files, and save them to the device.

    + +

    To test your application's implementation of the manual download procedure, you must upload +your application to Android Market as a "draft" to make your expansion files available for +download:

    + +
      +
    1. Upload your APK and corresponding expansion files using the Android Market Developer +Console.
    2. +
    3. Fill in the necessary application details (title, screenshots, etc.). You can come back and +finalize these details before publishing your application. +

      Click the Save button. Do not click Publish. This saves +the application as a draft, such that your application is not published for Android Market users, +but the expansion files are available for you to test the download process.

    4. +
    5. Install the application on your test device using the Eclipse tools or {@code adb}.
    6. +
    7. Launch the app.
    8. +
    + +

    If everything works as expected, your application should begin downloading the expansion +files as soon as the main activity starts.

    + + + + +

    Updating Your Application

    + +

    One of the great benefits to using expansion files on Android Market is the ability to +update your application without re-downloading all of the original assets. Because Android Market +allows you to provide two expansion files with each APK, you can use the second file as a "patch" +that provides updates and new assets. Doing so avoids the +need to re-download the main expansion file which could be large and expensive for users.

    + +

    The patch expansion file is technically the same as the main expansion file and neither +the Android system nor Android Market perform actual patching between your main and patch expansion +files. Your application code must perform any necessary patches itself.

    + +

    If you use ZIP files as your expansion files, the APK Expansion Zip +Library that's included with the Expansion Downloader package includes the ability to merge your +patch file with the main expansion file.

    + +

    Note: Even if you only need to make changes to the patch +expansion file, you must still update the APK in order for Android Market to perform an update. +If you don't require code changes in the application, you should simply update the {@code versionCode} in the +manifest.

    + +

    As long as you don't change the main expansion file that's associated with the APK +in the Android Market Developer Console, users who previously installed your application will not +download the main expansion file. Existing users receive only the updated APK and the new patch +expansion file (retaining the previous main expansion file).

    + +

    Here are a few issues to keep in mind regarding updates to expansion files:

    + + + + + + + diff --git a/docs/html/guide/market/licensing/adding-licensing.jd b/docs/html/guide/market/licensing/adding-licensing.jd new file mode 100644 index 000000000000..d1fe8395db29 --- /dev/null +++ b/docs/html/guide/market/licensing/adding-licensing.jd @@ -0,0 +1,1072 @@ +page.title=Adding Licensing to Your App +parent.title=Application Licensing +parent.link=index.html +@jd:body + + + +
    + +
    + + + +

    After you've set up a publisher account and development environment (see Setting Up for Licensing), you are ready to add license verification to +your app with the License Verification Library (LVL).

    + +

    Adding license verification with the LVL involves these tasks:

    + +
      +
    1. Adding the licensing permission your application's manifest.
    2. +
    3. Implementing a Policy — you can choose one of the full implementations provided in the LVL or create your own.
    4. +
    5. Implementing an Obfuscator, if your {@code Policy} will cache any +license response data.
    6. +
    7. Adding code to check the license in your application's main +Activity.
    8. +
    9. Implementing a DeviceLimiter (optional and not recommended for +most applications).
    10. +
    + +

    The sections below describe these tasks. When you are done with the +integration, you should be able to compile your application successfully and you +can begin testing, as described in Setting Up the Test +Environment.

    + +

    For an overview of the full set of source files included in the LVL, see Summary of LVL Classes +and Interfaces.

    + + +

    Adding the Licensing Permission

    + +

    To use the Android Market application for sending a license check to the +server, your application must request the proper permission, +com.android.vending.CHECK_LICENSE. If your application does +not declare the licensing permission but attempts to initiate a license check, +the LVL throws a security exception.

    + +

    To request the licensing permission in your application, declare a <uses-permission> +element as a child of <manifest>, as follows:

    + +

    <uses-permission +android:name="com.android.vending.CHECK_LICENSE">

    + +

    For example, here's how the LVL sample application declares the permission: +

    + +
    <?xml version="1.0" encoding="utf-8"?>
    +
    +<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...">
    +    <!-- Devices >= 3 have version of Android Market that supports licensing. -->
    +    <uses-sdk android:minSdkVersion="3" />
    +    <!-- Required permission to check licensing. -->
    +    <uses-permission android:name="com.android.vending.CHECK_LICENSE" />
    +    ...
    +</manifest>
    +
    + +

    Note: Currently, you cannot declare the +CHECK_LICENSE permission in the LVL library project's manifest, +because the SDK Tools will not merge it into the manifests of dependent +applications. Instead, you must declare the permission in each dependent +application's manifest.

    + + +

    Implementing a Policy

    + + + +

    Android Market licensing service does not itself determine whether a +given user with a given license should be granted access to your application. +Rather, that responsibility is left to a {@code Policy} implementation that you provide +in your application.

    + +

    Policy is an interface declared by the LVL that is designed to hold your +application's logic for allowing or disallowing user access, based on the result +of a license check. To use the LVL, your application must provide an +implementation of {@code Policy}.

    + +

    The {@code Policy} interface declares two methods, allowAccess() and +processServerResponse(), which are called by a {@code LicenseChecker} +instance when processing a response from the license server. It also declares an +enum called LicenseResponse, which specifies the license response +value passed in calls to processServerResponse().

    + + + +

    To simplify the process of adding licensing to your application and to +provide an illustration of how a {@code Policy} should be designed, the LVL includes +two full {@code Policy} implementations that you can use without modification or +adapt to your needs:

    + + + +

    For most applications, the use of ServerManagedPolicy is highly +recommended. ServerManagedPolicy is the LVL default and is integrated with +the LVL sample application.

    + + +

    Guidelines for custom policies

    + +

    In your licensing implementation, you can use one of the complete policies +provided in the LVL (ServerManagedPolicy or StrictPolicy) or you can create a +custom policy. For any type of custom policy, there are several important design +points to understand and account for in your implementation.

    + +

    The licensing server applies general request limits to guard against overuse +of resources that could result in denial of service. When an application exceeds +the request limit, the licensing server returns a 503 response, which gets +passed through to your application as a general server error. This means that no +license response will be available to the user until the limit is reset, which +can affect the user for an indefinite period.

    + +

    If you are designing a custom policy, we recommend that the {@code Policy}: +

      + +
    1. Caches (and properly obfuscates) the most recent successful license response +in local persistent storage.
    2. +
    3. Returns the cached response for all license checks, for as long as the +cached response is valid, rather than making a request to the licensing server. +Setting the response validity according to the server-provided VT +extra is highly recommended. See Server Response Extras +for more information.
    4. +
    5. Uses an exponential backoff period, if retrying any requests the result in +errors. Note that the Android Market client automatically retries failed +requests, so in most cases there is no need for your {@code Policy} to retry them.
    6. +
    7. Provides for a "grace period" that allows the user to access your +application for a limited time or number of uses, while a license check is being +retried. The grace period benefits the user by allowing access until the next +license check can be completed successfully and it benefits you by placing a +hard limit on access to your application when there is no valid license response +available.
    8. +
    + +

    Designing your {@code Policy} according to the guidelines listed above is critical, +because it ensures the best possible experience for users while giving you +effective control over your application even in error conditions.

    + +

    Note that any {@code Policy} can use settings provided by the licensing server to +help manage validity and caching, retry grace period, and more. Extracting the +server-provided settings is straightforward and making use of them is highly +recommended. See the ServerManagedPolicy implementation for an example of how to +extract and use the extras. For a list of server settings and information about +how to use them, see Server Response +Extras.

    + +

    ServerManagedPolicy

    + + + +

    The LVL includes a full and recommended implementation of the {@code Policy} +interface called ServerManagedPolicy. The implementation is integrated with the +LVL classes and serves as the default {@code Policy} in the library.

    + +

    ServerManagedPolicy provides all of the handling for license and retry +responses. It caches all of the response data locally in a +{@link android.content.SharedPreferences} file, obfuscating it with the +application's {@code Obfuscator} implementation. This ensures that the license response +data is secure and persists across device power cycles. ServerManagedPolicy +provides concrete implementations of the interface methods +processServerResponse() and allowAccess() and also +includes a set of supporting methods and types for managing license +responses.

    + +

    Importantly, a key feature of ServerMangedPolicy is its use of +server-provided settings as the basis for managing licensing across an +application's refund period and through varying network and error conditions. +When an application contacts the Android Market server for a license check, the +server appends several settings as key-value pairs in the extras field of certain +license response types. For example, the server provides recommended values for the +application's license validity period, retry grace period, and maximum allowable +retry count, among others. ServerManagedPolicy extracts the values from the +license response in its processServerResponse() method and checks +them in its allowAccess() method. For a list of the server-provided +settings used by ServerManagedPolicy, see Server Response +Extras.

    + +

    For convenience, best performance, and the benefit of using license settings +from the Android Market server, using ServerManagedPolicy as your +licensing {@code Policy} is strongly recommended.

    + +

    If you are concerned about the security of license response data that is +stored locally in {@link android.content.SharedPreferences}, you can use a stronger obfuscation +algorithm or design a stricter {@code Policy} that does not store license data. The LVL +includes an example of such a {@code Policy} — see StrictPolicy for more information.

    + +

    To use ServerManagedPolicy, simply import it to your Activity, create an +instance, and pass a reference to the instance when constructing your +{@code LicenseChecker}. See Instantiate LicenseChecker and +LicenseCheckerCallback for more information.

    + +

    StrictPolicy

    + +

    The LVL includes an alternative full implementation of the {@code Policy} interface +called StrictPolicy. The StrictPolicy implementation provides a more restrictive +Policy than ServerManagedPolicy, in that it does not allow the user to access +the application unless a license response is received from the server at the +time of access that indicates that the user is licensed.

    + +

    The principal feature of StrictPolicy is that it does not store any +license response data locally, in a persistent store. Because no data is stored, +retry requests are not tracked and cached responses can not be used to fulfill +license checks. The {@code Policy} allows access only if:

    + + + +

    Using StrictPolicy is appropriate if your primary concern is to ensure that, +in all possible cases, no user will be allowed to access the application unless +the user is confirmed to be licensed at the time of use. Additionally, the +Policy offers slightly more security than ServerManagedPolicy — since +there is no data cached locally, there is no way a malicious user could tamper +with the cached data and obtain access to the application.

    + +

    At the same time, this {@code Policy} presents a challenge for normal users, since it +means that they won't be able to access the application when there is no network +(cell or Wi-Fi) connection available. Another side-effect is that your +application will send more license check requests to the server, since using a +cached response is not possible.

    + +

    Overall, this policy represents a tradeoff of some degree of user convenience +for absolute security and control over access. Consider the tradeoff carefully +before using this {@code Policy}.

    + +

    To use StrictPolicy, simply import it to your Activity, create an instance, +and pass a reference to it when constructing your {@code LicenseChecker}. See +Instantiate LicenseChecker and LicenseCheckerCallback +for more information.

    + +

    Implementing an Obfuscator

    + + + +

    A typical {@code Policy} implementation needs to save the license response data for +an application to a persistent store, so that it is accessible across +application invocations and device power cycles. For example, a {@code Policy} would +maintain the timestamp of the last successful license check, the retry count, +the license validity period, and similar information in a persistent store, +rather than resetting the values each time the application is launched. The +default {@code Policy} included in the LVL, ServerManagedPolicy, stores license response +data in a {@link android.content.SharedPreferences} instance, to ensure that the +data is persistent.

    + +

    Because the {@code Policy} will use stored license response data to determine whether +to allow or disallow access to the application, it must ensure that any +stored data is secure and cannot be reused or manipulated by a root user on a +device. Specifically, the {@code Policy} must always obfuscate the data before storing +it, using a key that is unique for the application and device. Obfuscating using +a key that is both application-specific and device-specific is critical, because +it prevents the obfuscated data from being shared among applications and +devices.

    + +

    The LVL assists the application with storing its license response data in a +secure, persistent manner. First, it provides an {@code Obfuscator} +interface that lets your application supply the obfuscation algorithm of its +choice for stored data. Building on that, the LVL provides the helper class +PreferenceObfuscator, which handles most of the work of calling the +application's {@code Obfuscator} class and reading and writing the obfuscated data in a +{@link android.content.SharedPreferences} instance.

    + +

    The LVL provides a full {@code Obfuscator} implementation called +AESObfuscator that uses AES encryption to obfuscate data. You can +use AESObfuscator in your application without modification or you +can adapt it to your needs. For more information, see the next section.

    + + +

    AESObfuscator

    + +

    The LVL includes a full and recommended implementation of the {@code Obfuscator} +interface called AESObfuscator. The implementation is integrated with the +LVL sample application and serves as the default {@code Obfuscator} in the library.

    + +

    AESObfuscator provides secure obfuscation of data by using AES to +encrypt and decrypt the data as it is written to or read from storage. +The {@code Obfuscator} seeds the encryption using three data fields provided +by the application:

    + +
      +
    1. A salt — an array of random bytes to use for each (un)obfuscation.
    2. +
    3. An application identifier string, typically the package name of the application.
    4. +
    5. A device identifier string, derived from as many device-specific sources +as possible, so as to make it as unique.
    6. +
    + +

    To use AESObfuscator, first import it to your Activity. Declare a private +static final array to hold the salt bytes and initialize it to 20 randomly +generated bytes.

    + +
        ...
    +    // Generate 20 random bytes, and put them here.
    +    private static final byte[] SALT = new byte[] {
    +     -46, 65, 30, -128, -103, -57, 74, -64, 51, 88, -95,
    +     -45, 77, -117, -36, -113, -11, 32, -64, 89
    +     };
    +    ...
    +
    + +

    Next, declare a variable to hold a device identifier and generate a value for +it in any way needed. For example, the sample application included in the LVL +queries the system settings for the +android.Settings.Secure.ANDROID_ID, which is unique to each device. +

    + +

    Note that, depending on the APIs you use, your application might need to +request additional permissions in order to acquire device-specific information. +For example, to query the {@link android.telephony.TelephonyManager} to obtain +the device IMEI or related data, the application will also need to request the +android.permission.READ_PHONE_STATE permission in its manifest.

    + +

    Before requesting new permissions for the sole purpose of acquiring +device-specific information for use in your {@code Obfuscator}, consider +how doing so might affect your application or its filtering on Android Market +(since some permissions can cause the SDK build tools to add +the associated <uses-feature>).

    + +

    Finally, construct an instance of AESObfuscator, passing the salt, +application identifier, and device identifier. You can construct the instance +directly, while constructing your {@code Policy} and {@code LicenseChecker}. For example:

    + +
        ...
    +    // Construct the LicenseChecker with a Policy.
    +    mChecker = new LicenseChecker(
    +        this, new ServerManagedPolicy(this,
    +            new AESObfuscator(SALT, getPackageName(), deviceId)),
    +        BASE64_PUBLIC_KEY  // Your public licensing key.
    +        );
    +    ...
    +
    + +

    For a complete example, see MainActivity in the LVL sample application.

    + + +

    Checking the License from an Activity

    + +

    Once you've implemented a {@code Policy} for managing access to your application, the +next step is to add a license check to your application, which initiates a query +to the licensing server if needed and manages access to the application based on +the license response. All of the work of adding the license check and handling +the response takes place in your main {@link android.app.Activity} source file. +

    + +

    To add the license check and handle the response, you must:

    + +
      +
    1. Add imports
    2. +
    3. Implement LicenseCheckerCallback as a private inner class
    4. +
    5. Create a Handler for posting from LicenseCheckerCallback to the UI thread
    6. +
    7. Instantiate LicenseChecker and LicenseCheckerCallback
    8. +
    9. Call checkAccess() to initiate the license check
    10. +
    11. Embed your public key for licensing
    12. +
    13. Call your LicenseChecker's onDestroy() method to close IPC connections.
    14. +
    + +

    The sections below describe these tasks.

    + +

    Overview of license check and response

    + + + +

    In most cases, you should add the license check to your application's main +{@link android.app.Activity}, in the {@link android.app.Activity#onCreate onCreate()} method. This +ensures that when the user launches your application directly, the license check +will be invoked immediately. In some cases, you can add license checks in other +locations as well. For example, if your application includes multiple Activity +components that other applications can start by {@link android.content.Intent}, +you could add license checks in those Activities.

    + +

    A license check consists of two main actions:

    + + + +
    + + +
    Figure 6. Overview of a +typical license check interaction.
    +
    + +

    The diagram above illustrates how a typical license check takes place:

    + +
      +
    1. Code in the application's main Activity instantiates {@code LicenseCheckerCallback} +and {@code LicenseChecker} objects. When constructing {@code LicenseChecker}, the code passes in +{@link android.content.Context}, a {@code Policy} implementation to use, and the +publisher account's public key for licensing as parameters.
    2. +
    3. The code then calls the checkAccess() method on the +{@code LicenseChecker} object. The method implementation calls the {@code Policy} to determine +whether there is a valid license response cached locally, in +{@link android.content.SharedPreferences}. +
        +
      • If so, the checkAccess() implementation calls + allow().
      • +
      • Otherwise, the {@code LicenseChecker} initiates a license check request that is sent + to the licensing server.
      • +
      + +

      Note: The licensing server always returns +LICENSED when you perform a license check of a draft application.

      +
    4. +
    5. When a response is received, {@code LicenseChecker} creates a LicenseValidator that +verifies the signed license data and extracts the fields of the response, then +passes them to your {@code Policy} for further evaluation. +
        +
      • If the license is valid, the {@code Policy} caches the response in +{@link android.content.SharedPreferences} and notifies the validator, which then calls the +allow() method on the {@code LicenseCheckerCallback} object.
      • +
      • If the license not valid, the {@code Policy} notifies the validator, which calls +the dontAllow() method on {@code LicenseCheckerCallback}.
      • +
      +
    6. +
    7. In case of a recoverable local or server error, such as when the network is +not available to send the request, {@code LicenseChecker} passes a {@code RETRY} response to +your {@code Policy} object's processServerResponse() method. +

      Also, both the {@code allow()} and {@code dontAllow()} callback methods receive a +reason argument. The {@code allow()} method's reason is usually {@code +Policy.LICENSED} or {@code Policy.RETRY} and the {@code dontAllow()} reason is usually {@code +Policy.NOT_LICENSED} or {@code Policy.RETRY}. These response values are useful so you can show +an appropriate response for the user, such as by providing a "Retry" button when {@code +dontAllow()} responds with {@code Policy.RETRY}, which might have been because the service was +unavailable.

    8. +
    9. In case of a application error, such as when the application attempts to +check the license of an invalid package name, {@code LicenseChecker} passes an error +response to the LicenseCheckerCallback's applicationError() +method.
    10. +
    + +

    Note that, in addition to initiating the license check and handling the +result, which are described in the sections below, your application also needs +to provide a Policy implementation and, if the {@code Policy} +stores response data (such as ServerManagedPolicy), an Obfuscator implementation.

    + + +

    Add imports

    + +

    First, open the class file of the application's main Activity and import +{@code LicenseChecker} and {@code LicenseCheckerCallback} from the LVL package.

    + +
        import com.android.vending.licensing.LicenseChecker;
    +    import com.android.vending.licensing.LicenseCheckerCallback;
    + +

    If you are using the default {@code Policy} implementation provided with the LVL, +ServerManagedPolicy, import it also, together with the AESObfuscator. If you are +using a custom {@code Policy} or {@code Obfuscator}, import those instead.

    + +
        import com.android.vending.licensing.ServerManagedPolicy;
    +    import com.android.vending.licensing.AESObfuscator;
    + +

    Implement LicenseCheckerCallback as a private inner class

    + +

    {@code LicenseCheckerCallback} is an interface provided by the LVL for handling +result of a license check. To support licensing using the LVL, you must +implement {@code LicenseCheckerCallback} and +its methods to allow or disallow access to the application.

    + +

    The result of a license check is always a call to one of the +{@code LicenseCheckerCallback} methods, made based on the validation of the response +payload, the server response code itself, and any additional processing provided +by your {@code Policy}. Your application can implement the methods in any way needed. In +general, it's best to keep the methods simple, limiting them to managing UI +state and application access. If you want to add further processing of license +responses, such as by contacting a backend server or applying custom constraints, +you should consider incorporating that code into your {@code Policy}, rather than +putting it in the {@code LicenseCheckerCallback} methods.

    + +

    In most cases, you should declare your implementation of +{@code LicenseCheckerCallback} as a private class inside your application's main +Activity class.

    + +

    Implement the allow() and dontAllow() methods as +needed. To start with, you can use simple result-handling behaviors in the +methods, such as displaying the license result in a dialog. This helps you get +your application running sooner and can assist with debugging. Later, after you +have determined the exact behaviors you want, you can add more complex handling. +

    + +

    Some suggestions for handling unlicensed responses in +dontAllow() include:

    + + + +

    The example below shows how the LVL sample application implements +{@code LicenseCheckerCallback}, with methods that display the license check result in a +dialog.

    + +
    +private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
    +    public void allow(int reason) {
    +        if (isFinishing()) {
    +            // Don't update UI if Activity is finishing.
    +            return;
    +        }
    +        // Should allow user access.
    +        displayResult(getString(R.string.allow));
    +    }
    +
    +    public void dontAllow(int reason) {
    +        if (isFinishing()) {
    +            // Don't update UI if Activity is finishing.
    +            return;
    +        }
    +        displayResult(getString(R.string.dont_allow));
    +        
    +        if (reason == Policy.RETRY) {
    +            // If the reason received from the policy is RETRY, it was probably
    +            // due to a loss of connection with the service, so we should give the
    +            // user a chance to retry. So show a dialog to retry.
    +            showDialog(DIALOG_RETRY);
    +        } else {
    +            // Otherwise, the user is not licensed to use this app.
    +            // Your response should always inform the user that the application
    +            // is not licensed, but your behavior at that point can vary. You might
    +            // provide the user a limited access version of your app or you can
    +            // take them to Android Market to purchase the app.
    +            showDialog(DIALOG_GOTOMARKET);
    +        }
    +    }
    +}
    +
    + +

    Additionally, you should implement the applicationError() +method, which the LVL calls to let your application handle errors that are not +retryable. For a list of such errors, see Server +Response Codes in the Licensing Reference. You can implement +the method in any way needed. In most cases, the +method should log the error code and call dontAllow().

    + +

    Create a Handler for posting from LicenseCheckerCallback +to the UI thread

    + +

    During a license check, the LVL passes the request to the Android Market +application, which handles communication with the licensing server. The LVL +passes the request over asynchronous IPC (using {@link android.os.Binder}) so +the actual processing and network communication do not take place on a thread +managed by your application. Similarly, when the Android Market application +receives the result, it invokes a callback method over IPC, which in turn +executes in an IPC thread pool in your application's process.

    + +

    The {@code LicenseChecker} class manages your application's IPC communication with +the Android Market application, including the call that sends the request and +the callback that receives the response. {@code LicenseChecker} also tracks open license +requests and manages their timeouts.

    + +

    So that it can handle timeouts properly and also process incoming responses +without affecting your application's UI thread, {@code LicenseChecker} spawns a +background thread at instantiation. In the thread it does all processing of +license check results, whether the result is a response received from the server +or a timeout error. At the conclusion of processing, the LVL calls your +{@code LicenseCheckerCallback} methods from the background thread.

    + +

    To your application, this means that:

    + +
      +
    1. Your {@code LicenseCheckerCallback} methods will be invoked, in many cases, from a +background thread.
    2. +
    3. Those methods won't be able to update state or invoke any processing in the +UI thread, unless you create a Handler in the UI thread and have your callback +methods post to the Handler.
    4. +
    + +

    If you want your {@code LicenseCheckerCallback} methods to update the UI thread, +instantiate a {@link android.os.Handler} in the main Activity's +{@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method, +as shown below. In this example, the LVL sample application's +{@code LicenseCheckerCallback} methods (see above) call displayResult() to +update the UI thread through the Handler's +{@link android.os.Handler#post(java.lang.Runnable) post()} method.

    + +
    private Handler mHandler;
    +
    +    @Override
    +    public void onCreate(Bundle savedInstanceState) {
    +        ...
    +        mHandler = new Handler();
    +    }
    +
    + +

    Then, in your {@code LicenseCheckerCallback} methods, you can use Handler methods to +post Runnable or Message objects to the Handler. Here's how the sample +application included in the LVL posts a Runnable to a Handler in the UI thread +to display the license status.

    + +
        private void displayResult(final String result) {
    +        mHandler.post(new Runnable() {
    +            public void run() {
    +                mStatusText.setText(result);
    +                setProgressBarIndeterminateVisibility(false);
    +                mCheckLicenseButton.setEnabled(true);
    +            }
    +        });
    +    }
    +
    + +

    Instantiate LicenseChecker and LicenseCheckerCallback

    + +

    In the main Activity's +{@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method, +create private instances of LicenseCheckerCallback and {@code LicenseChecker}. You must +instantiate {@code LicenseCheckerCallback} first, because you need to pass a reference +to that instance when you call the constructor for {@code LicenseChecker}.

    + +

    When you instantiate {@code LicenseChecker}, you need to pass in these parameters:

    + + + +

    If you are using ServerManagedPolicy, you won't need to access the class +directly, so you can instantiate it in the {@code LicenseChecker} constructor, +as shown in the example below. Note that you need to pass a reference to a new +Obfuscator instance when you construct ServerManagedPolicy.

    + +

    The example below shows the instantiation of {@code LicenseChecker} and +{@code LicenseCheckerCallback} from the onCreate() method of an Activity +class.

    + +
    public class MainActivity extends Activity {
    +    ...
    +    private LicenseCheckerCallback mLicenseCheckerCallback;
    +    private LicenseChecker mChecker;
    +
    +    @Override
    +    public void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        ...
    +        // Construct the LicenseCheckerCallback. The library calls this when done.
    +        mLicenseCheckerCallback = new MyLicenseCheckerCallback();
    +
    +        // Construct the LicenseChecker with a Policy.
    +        mChecker = new LicenseChecker(
    +            this, new ServerManagedPolicy(this,
    +                new AESObfuscator(SALT, getPackageName(), deviceId)),
    +            BASE64_PUBLIC_KEY  // Your public licensing key.
    +            );
    +        ...
    +    }
    +}
    +
    + + +

    Note that {@code LicenseChecker} calls the {@code LicenseCheckerCallback} methods from the UI +thread only if there is valid license response cached locally. If the +license check is sent to the server, the callbacks always originate from the +background thread, even for network errors.

    + + +

    Call checkAccess() to initiate the license check

    + +

    In your main Activity, add a call to the checkAccess() method of the +{@code LicenseChecker} instance. In the call, pass a reference to your +{@code LicenseCheckerCallback} instance as a parameter. If you need to handle any +special UI effects or state management before the call, you might find it useful +to call checkAccess() from a wrapper method. For example, the LVL +sample application calls checkAccess() from a +doCheck() wrapper method:

    + +
        @Override
    +    public void onCreate(Bundle savedInstanceState) {
    +        super.onCreate(savedInstanceState);
    +        ...
    +        // Call a wrapper method that initiates the license check
    +        doCheck();
    +        ...
    +    }
    +    ...
    +    private void doCheck() {
    +        mCheckLicenseButton.setEnabled(false);
    +        setProgressBarIndeterminateVisibility(true);
    +        mStatusText.setText(R.string.checking_license);
    +        mChecker.checkAccess(mLicenseCheckerCallback);
    +    }
    +
    + + +

    Embed your public key for licensing

    + +

    For each publisher account, the Android Market service automatically +generates a 2048-bit RSA public/private key pair that is used exclusively for +licensing. The key pair is uniquely associated with the publisher account and is +shared across all applications that are published through the account. Although +associated with a publisher account, the key pair is not the same as +the key that you use to sign your applications (or derived from it).

    + +

    The Android Market publisher site exposes the public key for licensing to any +developer signed in to the publisher account, but it keeps the private key +hidden from all users in a secure location. When an application requests a +license check for an application published in your account, the licensing server +signs the license response using the private key of your account's key pair. +When the LVL receives the response, it uses the public key provided by the +application to verify the signature of the license response.

    + +

    To add licensing to an application, you must obtain your publisher account's +public key for licensing and copy it into your application. Here's how to find +your account's public key for licensing:

    + +
      +
    1. Go to the Android Market publisher site and sign in. +Make sure that you sign in to the account from which the application you are +licensing is published (or will be published).
    2. +
    3. In the account home page, locate the "Edit profile" link and click it.
    4. +
    5. In the Edit Profile page, locate the "Licensing" pane, shown below. Your +public key for licensing is given in the "Public key" text box.
    6. +
    + +

    To add the public key to your application, simply copy/paste the key string +from the text box into your application as the value of the String variable +BASE64_PUBLIC_KEY. When you are copying, make sure that you have +selected the entire key string, without omitting any characters.

    + +

    Here's an example from the LVL sample application:

    + +
        public class MainActivity extends Activity {
    +        private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG ... "; //truncated for this example
    +    ...
    +    }
    +
    + +

    Call your LicenseChecker's onDestroy() method +to close IPC connections

    + +

    Finally, to let the LVL clean up before your application +{@link android.content.Context} changes, add a call to the {@code LicenseChecker}'s +onDestroy() method from your Activity's +{@link android.app.Activity#onDestroy()} implementation. The call causes the +{@code LicenseChecker} to properly close any open IPC connection to the Android Market +application's ILicensingService and removes any local references to the service +and handler.

    + +

    Failing to call the {@code LicenseChecker}'s onDestroy() method +can lead to problems over the lifecycle of your application. For example, if the +user changes screen orientation while a license check is active, the application +{@link android.content.Context} is destroyed. If your application does not +properly close the {@code LicenseChecker}'s IPC connection, your application will crash +when the response is received. Similarly, if the user exits your application +while a license check is in progress, your application will crash when the +response is received, unless it has properly called the +{@code LicenseChecker}'s onDestroy() method to disconnect from the service. +

    + +

    Here's an example from the sample application included in the LVL, where +mChecker is the {@code LicenseChecker} instance:

    + +
        @Override
    +    protected void onDestroy() {
    +        super.onDestroy();
    +        mChecker.onDestroy();
    +        ...
    +    }
    +
    + +

    If you are extending or modifying {@code LicenseChecker}, you might also need to call +the {@code LicenseChecker}'s finishCheck() method, to clean up any open IPC +connections.

    + +

    Implementing a DeviceLimiter

    + +

    In some cases, you might want your {@code Policy} to limit the number of actual +devices that are permitted to use a single license. This would prevent a user +from moving a licensed application onto a number of devices and using the +application on those devices under the same account ID. It would also prevent a +user from "sharing" the application by providing the account information +associated with the license to other individuals, who could then sign in to that +account on their devices and access the license to the application.

    + +

    The LVL supports per-device licensing by providing a +DeviceLimiter interface, which declares a single method, +allowDeviceAccess(). When a LicenseValidator is handling a response +from the licensing server, it calls allowDeviceAccess(), passing a +user ID string extracted from the response.

    + +

    If you do not want to support device limitation, no work is +required — the {@code LicenseChecker} class automatically uses a default +implementation called NullDeviceLimiter. As the name suggests, NullDeviceLimiter +is a "no-op" class whose allowDeviceAccess() method simply returns +a LICENSED response for all users and devices.

    + +
    +

    Caution: Per-device licensing is not recommended for +most applications because:

    + +
    + + + + + + + + + + + +

    Obfuscating Your Code

    + +

    To ensure the security of your application, particularly for a paid +application that uses licensing and/or custom constraints and protections, it's +very important to obfuscate your application code. Properly obfuscating your +code makes it more difficult for a malicious user to decompile the application's +bytecode, modify it — such as by removing the license check — +and then recompile it.

    + +

    Several obfuscator programs are available for Android applications, including +ProGuard, which also offers +code-optimization features. The use of ProGuard or a similar program to obfuscate +your code is strongly recommended for all applications that use Android +Market Licensing.

    + +

    Publishing a Licensed Application

    + +

    When you are finished testing your license implementation, you are ready to +publish the application on Android Market. Follow the normal steps to prepare, sign, and then publish the application. +

    + +

    Removing Copy Protection

    + +

    After uploading your licensed application, remember to remove copy protection +from the application, if it is currently used. To check and remove copy +protection, sign in to the publisher site and go the application's upload +details page. In the Publishing options section, make sure that the Copy +Protection radio button selection is "Off".

    + + +

    Where to Get Support

    + +

    If you have questions or encounter problems while implementing or deploying +publishing in your applications, please use the support resources listed in the +table below. By directing your queries to the correct forum, you can get the +support you need more quickly.

    + +

    Table 2. Developer support resources +for Android Market Licensing Service.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Support TypeResourceRange of Topics
    Development and testing issuesGoogle Groups: android-developers +LVL download and integration, library projects, {@code Policy} +questions, user experience ideas, handling of responses, {@code Obfuscator}, IPC, test +environment setup
    Stack Overflow: http://stackoverflow.com/questions/tagged/android
    Accounts, publishing, and deployment issuesAndroid +Market Help ForumPublisher accounts, licensing key pair, test accounts, server +responses, test responses, application deployment and results
    Market +Licensing Support FAQ
    LVL issue trackerMarketlicensing +project issue trackerBug and issue reports related specifically to the LVL source code classes +and interface implementations
    + +

    For general information about how to post to the groups listed above, see Developer Forums document +in the Resources tab.

    + + diff --git a/docs/html/guide/market/licensing/index.jd b/docs/html/guide/market/licensing/index.jd new file mode 100644 index 000000000000..f08176d57101 --- /dev/null +++ b/docs/html/guide/market/licensing/index.jd @@ -0,0 +1,61 @@ +page.title=Application Licensing +@jd:body + + +

    Android Market offers a licensing service that lets you enforce licensing policies for +applications that you publish on Android Market. With Android Market Licensing, your application can +query Android Market at run time to obtain the licensing status for the current user, then allow or +disallow further use as appropriate.

    + +

    Using the service, you can apply a flexible licensing policy on an application-by-application +basis—each application can enforce licensing in the way most appropriate for it. If necessary, +an application can apply custom constraints based on the licensing status obtained from Android +Market. For example, an application can check the licensing status and then apply custom constraints +that allow the user to run it unlicensed for a specific validity period. An application can also +restrict use of the application to a specific device, in addition to any other constraints.

    + +

    The licensing service is a secure means of controlling access to your applications. When an +application checks the licensing status, the Android Market server signs the licensing status +response using a key pair that is uniquely associated with the publisher account. Your application +stores the public key in its compiled .apk file and uses it to verify the licensing +status response.

    + +

    Any application that you publish through Android Market can use the Android Market Licensing +service. No special account or registration is needed. Additionally, because the service uses no +dedicated framework APIs, you can add licensing to any application that uses a minimum API level of +3 or higher.

    + +

    Note: The Android Market Licensing service is primarily intended +for paid applications that wish to verify that the current user did in fact pay for the application +on Android Market. However, any application (including free apps) may use the licensing service +to initiate the download of an APK expansion file. In which case, the request that your application +sends to the licensing service is not to check whether the user paid for the app, but to request the +URL of the expansion files. For information about downloading expansion files for your application, +read the guide to APK Expansion Files.

    + + +

    To learn more about Android Market's application licensing service and start integrating it into +your applications, read the following documents:

    + +
    +
    Licensing +Overview
    +
    Describes how the service works and what a typical licensing implementation looks +like.
    +
    Setting Up for +Licensing
    +
    Explains how to set up your Android Market account, development environment, and +testing environment in order to add licensing to your app.
    +
    Adding +Licensing to Your App
    +
    Provides a step-by-step guide to add licensing verification to your application.
    +
    Licensing +Reference
    +
    Provides detailed information about the licensing library's classes and the service response +codes.
    +
    + + + + + diff --git a/docs/html/guide/market/licensing/licensing-reference.jd b/docs/html/guide/market/licensing/licensing-reference.jd new file mode 100644 index 000000000000..ac5d59618b22 --- /dev/null +++ b/docs/html/guide/market/licensing/licensing-reference.jd @@ -0,0 +1,439 @@ +page.title=Licensing Reference +parent.title=Application Licensing +parent.link=index.html +@jd:body + + + +
    + +
    + + +

    LVL Classes and Interfaces

    + +

    Table 1 lists all of the source files in the License Verification +Library (LVL) available through the Android SDK. All of the files are part of +the com.android.vending.licensing package.

    + +

    Table 1. Summary of LVL library +classes and interfaces.

    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    CategoryNameDescription
    License check and resultLicenseCheckerClass that you instantiate (or subclass) to initiate a license check.
    LicenseCheckerCallbackInterface that you implement to handle result of the license check.
    PolicyPolicyInterface that you implement to determine whether to allow +access to the application, based on the license response.
    ServerManagedPolicyDefault {@code Policy} implementation. Uses settings provided by the +licensing server to manage local storage of license data, license validity, +retry.
    StrictPolicyAlternative {@code Policy} implementation. Enforces licensing based on a direct +license response from the server only. No caching or request retry.
    Data obfuscation
    (optional)
    ObfuscatorInterface that you implement if you are using a {@code Policy} (such as +ServerManagedPolicy) that caches license response data in a persistent store. +Applies an obfuscation algorithm to encode and decode data being written or +read.
    AESObfuscatorDefault Obfuscator implementation that uses AES encryption/decryption +algorithm to obfuscate/unobfuscate data.
    Device limitation
    (optional)
    DeviceLimiterInterface that you implement if you want to restrict use of an +application to a specific device. Called from LicenseValidator. Implementing +DeviceLimiter is not recommended for most applications because it requires a +backend server and may cause the user to lose access to licensed applications, +unless designed with care.
    NullDeviceLimiterDefault DeviceLimiter implementation that is a no-op (allows access to all +devices).
    Library core, no integration neededResponseDataClass that holds the fields of a license response.
    LicenseValidatorClass that decrypts and verifies a response received from the licensing +server.
    ValidationExceptionClass that indicates errors that occur when validating the integrity of data +managed by an Obfuscator.
    PreferenceObfuscatorUtility class that writes/reads obfuscated data to the system's +{@link android.content.SharedPreferences} store.
    ILicensingServiceOne-way IPC interface over which a license check request is passed to the +Android Market client.
    ILicenseResultListenerOne-way IPC callback implementation over which the application receives an +asynchronous response from the licensing server.
    +
    + + +

    Server Response Codes

    + +

    Table 2 lists all of the license response codes supported by the +licensing server. In general, an application should handle all of these response +codes. By default, the LicenseValidator class in the LVL provides all of the +necessary handling of these response codes for you.

    + +

    Table 2. Summary of response codes +returned by the Android Market server in a license response.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Response CodeDescriptionSigned?ExtrasComments
    {@code LICENSED}The application is licensed to the user. The user has purchased the +application or the application only exists as a draft.YesVTGT, GRAllow access according to {@code Policy} constraints.
    {@code LICENSED_OLD_KEY}The application is licensed to the user, but there is an updated application +version available that is signed with a different key. Yes VT, GT, GR, UTOptionally allow access according to {@code Policy} constraints. +

    Can indicate that the key pair used by the installed +application version is invalid or compromised. The application can allow access +if needed or inform the user that an upgrade is available and limit further use +until upgrade.

    +
    {@code NOT_LICENSED}The application is not licensed to the user.NoDo not allow access.
    {@code ERROR_CONTACTING_SERVER}Local error — the Android Market application was not able to reach the +licensing server, possibly because of network availability problems. NoRetry the license check according to {@code Policy} retry limits.
    {@code ERROR_SERVER_FAILURE}Server error — the server could not load the publisher account's key +pair for licensing.NoRetry the license check according to {@code Policy} retry limits. +
    {@code ERROR_INVALID_PACKAGE_NAME}Local error — the application requested a license check for a package +that is not installed on the device. No Do not retry the license check. +

    Typically caused by a development error.

    +
    {@code ERROR_NON_MATCHING_UID}Local error — the application requested a license check for a package +whose UID (package, user ID pair) does not match that of the requesting +application. No Do not retry the license check. +

    Typically caused by a development error.

    +
    {@code ERROR_NOT_MARKET_MANAGED}Server error — the application (package name) was not recognized by +Android Market. NoDo not retry the license check. +

    Can indicate that the application was not published +through Android Market or that there is an development error in the licensing +implementation.

    +
    + +

    Note: As documented in +Setting Up The Testing Environment, the response code can be manually +overridden for the application developer and any registered test users via the +Android Market publisher site. +

    +Additionally, as noted above, applications that are in draft mode (in other +words, applications that have been uploaded but have never been +published) will return {@code LICENSED} for all users, even if not listed as a test +user. Since the application has never been offered for download, it is assumed +that any users running it must have obtained it from an authorized channel for +testing purposes.

    + + + + +

    Server Response Extras

    + +

    To assist your application in managing access to the application across the application refund +period and provide other information, The licensing server includes several pieces of +information in the license responses. Specifically, the service provides recommended values for the +application's license validity period, retry grace period, maximum allowable retry count, and other +settings. If your application uses APK +expansion files, the response also includes the file names, sizes, and URLs. The server appends +the settings as key-value pairs in the license response "extras" field.

    + +

    Any {@code Policy} implementation can extract the extras settings from the license +response and use them as needed. The LVL default {@code Policy} implementation, {@code +ServerManagedPolicy}, serves as a working +implementation and an illustration of how to obtain, store, and use the +settings.

    + +

    Table 3. Summary of +license-management settings supplied by the Android Market server in a license +response.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ExtraDescription
    {@code VT}License validity timestamp. Specifies the date/time at which the current +(cached) license response expires and must be rechecked on the licensing server. See the section +below about License validity period. +
    {@code GT}Grace period timestamp. Specifies the end of the period during which a +Policy may allow access to the application, even though the response status is +{@code RETRY}.

    The value is managed by the server, however a typical value would be 5 +or more days. See the section +below about Retry period and maximum retry count.

    {@code GR}Maximum retries count. Specifies how many consecutive {@code RETRY} license checks +the {@code Policy} should allow, before denying the user access to the application. +

    The value is managed by the server, however a typical value would be "10" or +higher. See the section +below about Retry period and maximum retry count.

    {@code UT}Update timestamp. Specifies the day/time when the most recent update to +this application was uploaded and published.

    The server returns this extra +only for {@code LICENSED_OLD_KEYS} responses, to allow the {@code Policy} to determine how much +time has elapsed since an update was published with new licensing keys before +denying the user access to the application.

    {@code FILE_URL1} or {@code FILE_URL2}The URL for an expansion file (1 is for the main file, 2 is the patch file). Use this to +download the file over HTTP.
    {@code FILE_NAME1} or {@code FILE_NAME2}The expansion file's name (1 is for the main file, 2 is the patch file). You must use this +name when saving the file on the device.
    {@code FILE_SIZE1} or {@code FILE_SIZE2}The size of the file in bytes (1 is for the main file, 2 is the patch file). Use this to +assist with downloading and to ensure that enough space is available on the device's shared +storage location before downloading.
    + + + +

    License validity period

    + +

    The Android Market licensing server sets a license validity period for all +downloaded applications. The period expresses the interval of time over which an +application's license status should be considered as unchanging and cacheable by +a licensing {@code Policy} in the application. The licensing server includes the +validity period in its response to all license checks, appending an +end-of-validity timestamp to the response as an extra under the key {@code VT}. A +{@code Policy} can extract the VT key value and use it to conditionally allow access to +the application without rechecking the license, until the validity period +expires.

    + +

    The license validity signals to a licensing {@code Policy} when it must recheck the +licensing status with the licensing server. It is not intended to imply +whether an application is actually licensed for use. That is, when an +application's license validity period expires, this does not mean that the +application is no longer licensed for use — rather, it indicates only that +the {@code Policy} must recheck the licensing status with the server. It follows that, +as long as the license validity period has not expired, it is acceptable for the +{@code Policy} to cache the initial license status locally and return the cached license +status instead of sending a new license check to the server.

    + +

    The licensing server manages the validity period as a means of helping the +application properly enforce licensing across the refund period offered by +Android Market for paid applications. It sets the validity period based on +whether the application was purchased and, if so, how long ago. Specifically, +the server sets a validity period as follows:

    + + + +

    The {@code ServerManagedPolicy} implementation uses the extracted timestamp +(mValidityTimestamp) as a primary condition for determining whether +to recheck the license status with the server before allowing the user access to +the application.

    + + +

    Retry period and maximum retry count

    + +

    In some cases, system or network conditions can prevent an application's +license check from reaching the licensing server, or prevent the server's +response from reaching the Android Market client application. For example, the +user might launch an application when there is no cell network or data +connection available—such as when on an airplane—or when the +network connection is unstable or the cell signal is weak.

    + +

    When network problems prevent or interrupt a license check, the Android +Market client notifies the application by returning a {@code RETRY} response code to +the {@code Policy}'s processServerResponse() method. In the case of system +problems, such as when the application is unable to bind with Android Market's +{@code ILicensingService} implementation, the {@code LicenseChecker} library itself calls the +Policy processServerResonse() method with a {@code RETRY} response code. +

    + +

    In general, the {@code RETRY} response code is a signal to the application that an +error has occurred that has prevented a license check from completing. + +

    The Android Market server helps an application to manage licensing under +error conditions by setting a retry "grace period" and a recommended maximum +retries count. The server includes these values in all license check responses, +appending them as extras under the keys {@code GT} and {@code GR}.

    + +

    The application {@code Policy} can extract the {@code GT} and {@code GR} extras and use them to +conditionally allow access to the application, as follows:

    + + + +

    The {@code ServerManagedPolicy} uses the server-supplied {@code GT} and {@code GR} values as +described above. The example below shows the conditional handling of the retry +responses in the allow() method. The count of {@code RETRY} responses is +maintained in the processServerResponse() method, not shown.

    + + +
        
    +public boolean allowAccess() {
    +    long ts = System.currentTimeMillis();
    +    if (mLastResponse == LicenseResponse.LICENSED) {
    +        // Check if the LICENSED response occurred within the validity timeout.
    +        if (ts <= mValidityTimestamp) {
    +            // Cached LICENSED response is still valid.
    +            return true;
    +        }
    +    } else if (mLastResponse == LicenseResponse.RETRY &&
    +                ts < mLastResponseTime + MILLIS_PER_MINUTE) {
    +        // Only allow access if we are within the retry period or we haven't used up our
    +        // max retries.
    +        return (ts <= mRetryUntil || mRetryCount <= mMaxRetries);
    +    }
    +    return false;
    +}
    + diff --git a/docs/html/guide/market/licensing/overview.jd b/docs/html/guide/market/licensing/overview.jd new file mode 100644 index 000000000000..3576e26653fa --- /dev/null +++ b/docs/html/guide/market/licensing/overview.jd @@ -0,0 +1,245 @@ +page.title=Licensing Overview +parent.title=Application Licensing +parent.link=index.html +@jd:body + + +
    +
    + +

    Quickview

    +
      +
    • Licensing allows you to verify your app was purchased from Android Market
    • +
    • Your app maintains control of how it enforces its licensing status
    • +
    • The service is free for all developers who publish on Android Market
    • +
    + +

    In this document

    +
      +
    1. License Responses are Secure
    2. +
    3. Licensing Verification Library
    4. +
    5. Requirements and Limitations
    6. +
    7. Replacement for Copy Protection
    8. +
    + +
    +
    + + +

    Android Market Licensing is a network-based service that lets an application query a trusted +Android Market licensing server to determine whether the application is licensed to the current +device user. The licensing service is based on the capability of the Android Market licensing server +to determine whether a given user is licensed to use a given application. Android Market considers a +user to be licensed if the user is a recorded purchaser of the application.

    + +

    The request starts when your application makes a request to a service hosted by +the Android Market client application. The Android Market application then sends a request to +the licensing server and receives the result. The Android Market application sends +the result to your application, which can allow or disallow further use of the +application as needed.

    + +

    Note: If a paid application has been uploaded to Android Market but +saved only as a draft application (the app is unpublished), the licensing server considers all users +to be licensed users of the application (because it's not even possible to purchase the app). +This exception is necessary in order for you to perform testing of your licensing +implementation.

    + + +
    + +

    Figure 1. Your application initiates a +license check through the License Verification Library and the Android Market +client, which handles communication with the Market server.

    +
    + + +

    To properly identify the user and determine the license status, the licensing server requires +information about the application and user—your application and the Android Market client work +together to assemble the information and the Android Market client passes it to the server.

    + +

    To help you add licensing to your application, the Android SDK provides a downloadable set of +library sources that you can include in your application project: the "Google Market Billing +package." The License Verification Library (LVL) is a library you can add to your application that +handles all of the licensing-related communication with the Android Market licensing service. With +the LVL added to your application, your application can determine its licensing status for the +current user by simply calling a method and implementing a callback that receives the status +response.

    + +

    Your application does not query the licensing server +directly, but instead calls the Android Market client over remote IPC to +initiate a license request. In the license request:

    + + + +

    You can choose when, and how often, you want your application to check its +license and you have full control over how it handles the response, verifies the +signed response data, and enforces access controls.

    + +

    Notice that during a license check, your application does not manage any +network connections or use any licensing related APIs in the Android platform.

    + + + + +

    License Responses are Secure

    + +

    To ensure the integrity of each license query, the server signs the license +response data using an RSA key pair that is shared exclusively between the Android Market +server and you.

    + +

    The licensing service generates a single licensing key pair for each +publisher account and exposes the public key in your account's profile page. You must copy the +public key from the web site and embed it in your application source code. The server retains the +private key internally and uses it to sign license responses for the applications you +publish with that account.

    + +

    When your application receives a signed response, it uses the embedded public +key to verify the data. The use of public key cryptography in the licensing +service makes it possible for the application to detect responses that have been +tampered with or that are spoofed.

    + + + + +

    Licensing Verification Library

    + +

    The Android SDK provides a downloadable component called the "Google Market Licensing package," +which includes the License Verification Library (LVL). The LVL greatly simplifies the process of +adding licensing to your application and helps ensure a more secure, robust implementation for your +application. The LVL provides internal classes that handle most of the standard operations of a +license query, such as contacting the Android Market client to initiate a license request and +verifying and validating the responses. It also exposes interfaces that let you easily plug in your +custom code for defining licensing policy and managing access as needed by your application. The key +LVL interfaces are:

    + +
    +
    {@code Policy}
    +
    Your implementation determines whether to allow access to the +application, based on the license response received from the server and any +other data available (such as from a backend server associated with your +application). The implementation can evaluate the various fields of the license +response and apply other constraints, if needed. The implementation also lets +you manage the handling of license checks that result in errors, such as network +errors.
    + +
    {@code LicenseCheckerCallback}
    +
    Your implementation manages access to the +application, based on the result of the {@code Policy} object's handling of the license +response. Your implementation can manage access in any way needed, including +displaying the license result in the UI or directing the user to purchase the +application (if not currently licensed).
    +
    + + +

    To help you get started with a {@code Policy}, the LVL provides two fully complete +{@code Policy} implementations that you can use without modification or adapt to your +needs:

    + +
    +
    {@code ServerManagedPolicy}
    +
    A flexible {@code Policy} +that uses settings provided by the licensing server to manage response caching +and access to the application while the device is offline (such as when the +user is on an airplane). For most applications, the use of +{@code ServerManagedPolicy} is highly recommended.
    + +
    {@code StrictPolicy}
    +
    A restrictive {@code Policy} that +does not cache any response data and allows the application access only +when the server returns a licensed response.
    +
    + +

    The LVL is available as a downloadable component of the Android SDK. The +component includes both the LVL itself and an example application that shows how +the library should be integrated with your application and how your application +should manage response data, UI interaction, and error conditions.

    + +

    The LVL sources are provided as an Android library project, which +means that you can maintain a single set of library sources and share them +across multiple applications. A full test environment is also available through +the SDK, so you can develop and test the licensing implementation in your +applications before publishing them, even if you don't have access to a +physical device.

    + + + + +

    Requirements and Limitations

    + +

    Android Market Licensing is designed to let you apply license controls to +applications that you publish through Android Market. The service is not +designed to let you control access to applications that are not published +through Android Market or that are run on devices that do not offer the Android +Market client.

    + +

    Here are some points to keep in mind as you implement licensing in your +application:

    + + + + + +

    Replacement for Copy Protection

    + +

    Android Market Licensing is a flexible, secure mechanism for controlling +access to your applications. It effectively replaces the Copy Protection +mechanism offered on Android Market and gives you wider distribution +potential for your applications.

    + + + +

    Although no license mechanism can completely prevent all unauthorized use, +the licensing service lets you control access for most types of normal usage, +across all compatible devices, locked or unlocked, that run Android 1.5 or +higher version of the platform.

    + +

    To begin adding application licensing to your application, continue to Setting Up for Licensing.

    + + + + + + diff --git a/docs/html/guide/market/licensing/setting-up.jd b/docs/html/guide/market/licensing/setting-up.jd new file mode 100644 index 000000000000..c79f90b6a64d --- /dev/null +++ b/docs/html/guide/market/licensing/setting-up.jd @@ -0,0 +1,707 @@ +page.title=Setting Up for Licensing +parent.title=Application Licensing +parent.link=index.html +@jd:body + + +
    + +
    + +

    Before you start adding license verification to your application, you need to set up your Android +Market publishing account, your development environment, and test accounts required to verify +your implementation.

    + + +

    Setting Up a Publisher Account

    + +

    If you don't already have a publisher account for Android Market, you need to register for one +using your Google account and agree to the terms of service on the Android Market publisher site:

    + +

    http://market.android.com/publish +

    + +

    For more information, see Publishing on Android Market.

    + +

    If you already have a publisher account on Android Market, use your existing +account to set up licensing.

    + +

    Using your publisher account on Android Market, you can:

    + + + +

    Administrative settings for licensing

    + +

    You can manage several +administrative controls for Android Market licensing on the publisher site. The controls are available +in the Edit Profile page, in the "Licensing" panel, shown in figure 1. The controls +let you:

    + + + + + +

    Figure 1. The Licensing +panel of your account's Edit Profile page lets you manage administrative +settings for licensing.

    + +

    For more information about how to work with test accounts and static test +responses, see Setting Up a Testing Environment, below. + + + +

    Setting Up the Development Environment

    + +

    Setting up your environment for licensing involves these tasks:

    + +
      +
    1. Setting up the runtime environment for development
    2. +
    3. Downloading the LVL into your SDK
    4. +
    5. Setting up the Licensing Verification Library
    6. +
    7. Including the LVL library project in your application
    8. +
    + +

    The sections below describe these tasks. When you are done with setup, +you can begin Adding +Licensing to Your App.

    + +

    To get started, you need to set up a proper runtime environment on which +you can run, debug, and test your application's implementation of license +checking and enforcement.

    + + +

    Setting up the runtime environment

    + +

    As described earlier, applications check licensing status not by contacting +the licensing server directly, but by binding to a service provided by the +Android Market application and initiating a license check request. The Android +Market service then handles the direct communication with the licensing server +and finally routes the response back to your application. To debug and test +licensing in your application, you need to set up a runtime environment that +includes the necessary Android Market service, so that your application is able +to send license check requests to the licensing server.

    + +

    There are two types of runtime environment that you can use:

    + + + +

    Running on a device

    + +

    To use an Android-powered device for +debugging and testing licensing, the device must:

    + + + +

    If Android Market is not preinstalled in the system image, your application won't +be able to communicate with the Android Market licensing server.

    + +

    For general information about how to set up a device for use in developing +Android applications, see Using Hardware Devices.

    + +

    Running on an Android emulator

    + +

    If you don't have a device available, you can use an Android emulator for debugging and testing +licensing.

    + +

    Because the Android platforms provided in the Android SDK do +not include Android Market, you need to download the Google APIs Add-On +platform, API level 8 (or higher), from the SDK repository. After downloading +the add-on, you need to create an AVD configuration that uses that system image. +

    + +

    The Google APIs Add-On does not include the full Android Market client. +However, it does provide:

    + + + +

    Several versions of the add-on are available through the SDK Manager, but only +Google APIs Add-On, API 8 (release 2) or higher includes the necessary Android +Market services.

    + + + +

    Figure 2. Google APIs +Add-On, API 8 (release 2) or higher lets you debug and test your licensing +implementation in an emulator.

    + +

    To set up an emulator for adding licensing to an application, follow +these steps:

    + +
      +
    1. Launch the Android SDK Manager.
    2. +
    3. In the Available Packages panel, select and download the +SDK component "Google APIs (Google Inc.) - API Level 8" (or higher) from the SDK +repository, as shown in figure 2. +

      When the download is complete, use the Android SDK Manager to +create a new AVD based on that component, described next.

    4. +
    5. In the Virtual +Devices panel of the Android SDK Manager, click +New and set the configuration details for the new AVD.
    6. +
    7. In the dialog that appears, assign a descriptive name to the AVD and then +use the "Target" menu to choose the "Google APIs (Google Inc.) - API Level 8" as +the system image to run on the new AVD. Set the other configuration details as +needed and then click Create AVD to finish. The SDK tools +create the new AVD configuration, which then appears in the list of available +Android Virtual Devices.
    8. +
    + +

    If you are not familiar with AVDs or how to use them, see Managing Virtual Devices.

    + +

    Updating your project configuration

    + +

    After you set up a runtime environment that meets the requirements described +above — either on an actual device or on an emulator — make sure to +update your application project or build scripts as needed, so that your compiled +.apk files that use licensing are deployed into that environment. +In particular, if you are developing in Eclipse, make sure that you set up a +Run/Debug Configuration that targets the appropriate device or AVD.

    + +

    You do not need to make any changes to your application's +build configuration, provided that the project is already configured to compile +against a standard Android 1.5 (API level 3) or higher library. For example: + +

    + +

    In general, adding licensing to an application should have no impact +whatsoever on the application's build configuration.

    + + +

    Downloading the LVL

    + +

    The License Verification Library (LVL) is a collection of helper classes that +greatly simplify the work that you need to do to add licensing to your +application. In all cases, we recommend that you download the LVL and use it as +the basis for the licensing implementation in your application.

    + +

    The LVL is available as a downloadable component of the Android SDK. The +component includes:

    + + + +

    To download the LVL component into your development environment, use the +Android SDK Manager. Launch the Android SDK Manager and then +select the "Market Licensing" component, as shown in figure 3. +Accept the terms and click Install Selected to begin the download.

    + + +

    Figure 3. The Market Licensing package contains the LVL and +the LVL sample application.

    + +

    When the download is complete, the Android SDK Manager installs both +the LVL library project and the example application into these directories:

    + +

    <sdk>/extras/google/market_licensing/library/ +  (the LVL library project)
    +<sdk>/extras/google/market_licensing/sample/  (the example +application)

    + +

    If you aren't familiar with how to download components into your SDK, see the +Adding SDK Components +document.

    + + +

    Setting Up the Licensing Verification Library

    + +

    After downloading the LVL to your computer, you need to set it up in your +development environment, either as an Android library project or by +copying (or importing) the library sources directly into your existing +application package. In general, using the LVL as a library project is recommended, +since it lets you reuse your licensing code across multiple applications and +maintain it more easily over time. Note that the LVL is not designed to be +compiled separately and added to an application as a static .jar file.

    + +

    Moving the library sources to a new location

    + +

    Because you will be customizing the LVL sources to some extent, you should +make sure to move or copy the library sources (the entire +directory at <sdk>/market_licensing/library/) +to a working directory outside of the SDK. You should then use the relocated +sources as your working set. If you are using a source-code management +system, add and track the sources that are in the working location rather +than those in default location in the SDK.

    + +

    Moving the library sources is important is because, when you later update the +Market licensing package, the SDK installs the new files to the same location as +the older files. Moving your working library files to a safe location ensures +that your work won't be inadvertently overwritten should you download a new +version of the LVL.

    + +

    Creating the LVL as a library project

    + + + +

    The recommended way of using the LVL is setting it up as a new Android +library project. A library project is a type of development project +that holds shared Android source code and resources. Other Android application +projects can reference the library project and, at build time, include its +compiled sources in their .apk files. In the context of licensing, +this means that you can do most of your licensing development once, in a library +project, then include the library sources in your various application projects. +In this way, you can easily maintain a uniform implementation of licensing +across all of your projects and maintain it centrally.

    + +

    The LVL is provided as a configured library project — once you have +downloaded it, you can start using it right away.

    + +

    If you are working in Eclipse with ADT, you need to add the LVL to your +workspace as a new development project, in the same way as you would a new +application project.

    + +
      +
    1. Use the New Project Wizard to create a new +project from existing sources. Select the LVL's library directory +(the directory containing the library's AndroidManifest.xml file) as the project +root.
    2. +
    3. When you are creating the library project, you can select any application +name, package, and set other fields as needed.
    4. +
    5. For the library's build target, select Android 1.5 (API level 3) or higher.
    6. +
    + +

    When created, the project is +predefined as a library project in its project.properties file, so +no further configuration is needed.

    + +

    For more information about how to create an application project or work with +library projects in Eclipse, see Managing Projects from +Eclipse with ADT.

    + + +

    Copying the LVL sources to your application

    + +

    As an alternative to adding the LVL as a library project, you can copy the +library sources directly into your application. To do so, copy (or import) the +LVL's library/src/com directory into your application's +src/ directory.

    + +

    If you add the LVL sources directly to your application, you can skip the +next section and start working with the library, as described in Adding +Licensing to Your App.

    + + +

    Including the LVL library project sources in your +application

    + +

    If you want to use the LVL sources as a library project, you need to add a +reference to the LVL library project in your application project properties. This tells +build tools to include the LVL library project sources in your application at +compile time. The process for adding a reference to a library project depends +on your development environment, as described below.

    + +

    If you are developing in Eclipse with ADT, you should already have added the +library project to your workspace, as described in the previous section. If you +haven't done that already, do it now before continuing.

    + +

    Next, open the application's project properties window, as shown below. +Select the "Android" properties group and click Add, then +choose the LVL library project (com_android_vending_licensing) and click +OK. For more information, see + +Managing Projects from Eclipse with ADT

    . + + + +

    Figure 4. If you are +working in Eclipse with ADT, you can add the LVL library project to your +application from the application's project properties.

    + + +

    If you are developing using the SDK command-line tools, navigate to the +directory containing your application project and open the +project.properties file. Add a line to the file that specifies the +android.library.reference.<n> key and the path to the +library. For example:

    + +
    android.library.reference.1=path/to/library_project
    + +

    Alternatively, you can use this command to update the project +properties, including the reference to the library project:

    + +
    android update lib-project
    +--target <target_ID> \
    +--path path/to/my/app_project \
    +--library path/to/my/library_project
    +
    + +

    For more information about working with library projects, +see +Setting up a Library Project.

    + + + + + + + + + + + + + + + + + + + + + +

    Setting Up the Testing Environment

    + +

    The Android Market publisher site provides configuration tools that let you +and others test licensing on your application before it is published. As you are +implementing licensing, you can make use of the publisher site tools to test +your application's Policy and handling of different licensing responses and +error conditions.

    + +

    The main components of the test environment for licensing include:

    + + + +

    Setting up the test environment properly involves:

    + +
      +
    1. Setting static test responses that are returned by the licensing server.
    2. +
    3. Setting up test accounts as needed.
    4. +
    5. Signing in properly to an emulator or device, before initiating a license check test.
    6. +
    + +

    The sections below provide more information.

    + + +

    Setting test responses for license checks

    + +

    Android Market provides a configuration setting in your publisher account +that lets you override the normal processing of a license check and return a +specified static response code. The setting is for testing only and applies +only to license checks for applications that you have uploaded, made by +any user signed in to an emulator or device using the credentials of the +publisher account or a registered test account. For other users, the server +always processes license checks according to normal rules.

    + +

    To set a test response for your account, sign in to your publisher account +and click "Edit Profile". In the Edit Profile page, locate the Test Response +menu in the Licensing panel, shown below. You can select from the full set of +valid server response codes to control the response or condition you want to +test in your application.

    + +

    In general, you should make sure to test your application's licensing +implementation with every response code available in the Test Response menu. +For a description of the codes, see Server +Response Codes in the Licensing Reference.

    + + +

    Figure 5. The Licensing +panel of your account's Edit Profile page, showing the Test Accounts field and the +Test Response menu.

    + +

    Note that the test response that you configure applies account-wide — +that is, it applies not to a single application, but to all +applications associated with the publisher account. If you are testing multiple +applications at once, changing the test response will affect all of those +applications on their next license check (if the user is signed in to +the emulator or device using the publisher account or a test account).

    + +

    Before you can successfully receive a test response for a license check, +you must sign in to the device or emulator on which the application +is installed, and from which it is querying the server. Specifically, you must +sign using either your publisher account or one of the test accounts that you +have set up. For more information about test accounts, see the next section.

    + +

    See Server +Response Codes for a list of +test responses available and their meanings.

    + + +

    Setting up test accounts

    + +

    In some cases, you might want to let multiple teams of developers test +licensing on applications that will ultimately be published through your +publisher account, but without giving them access to your publisher account's +sign-in credentials. To meet that need, the Android Market publisher site lets +you set up one or more optional test accounts — accounts that are +authorized to query the licensing server and receive static test responses from +your publisher account.

    + +

    Test accounts are standard Google accounts that you register on your +publisher account, such that they will receive the test response for +applications that you have uploaded. Developers can then sign in to their +devices or emulators using the test account credentials and initiate license +checks from installed applications. When the licensing server receives a license +check from a user of a test account, it returns the static test response +configured for the publisher account.

    + +

    Necessarily, there are limitations on the access and permissions given to +users signed in through test accounts, including:

    + + + +

    The table below summarizes the differences in capabilities, between the +publisher account, a test account, and any other account.

    + +

    Table 1. +Differences in account types for testing licensing.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Account TypeCan check license before upload?Can receive test response?Can set test response?
    Publisher accountYesYesYes
    Test accountNoYesNo
    OtherNoNoNo
    + +

    Registering test accounts on the publisher account

    + +

    To get started, you need to register each test account in your publisher +account. As shown in Figure 5, you +register test accounts in the Licensing panel of your publisher account's Edit +Profile page. Simply enter the accounts as a comma-delimited list and click +Save to save your profile changes.

    + +

    You can use any Google account as a test account. If you want to own and +control the test accounts, you can create the accounts yourself and distribute +the credentials to your developers or testers.

    + +

    Handling application upload and distribution for test +account users

    + +

    As mentioned above, users of test accounts can only receive static test +responses for applications that are uploaded to the publisher account. Since +those users do not have permission to upload applications, as the publisher you +will need to work with those users to collect apps for upload and distribute +uploaded apps for testing. You can handle collection and distribution in any way +that is convenient.

    + +

    Once an application is uploaded and becomes known to the licensing server, +developers and testers can continue modify the application in their local +development environment, without having to upload new versions. You only need to +upload a new version if the local application increments the +versionCode attribute in the manifest file.

    + +

    Distributing your public key to test account users

    + +

    The licensing server handles static test responses in the normal way, +including signing the license response data, adding extras parameters, and so +on. To support developers who are implementing licensing using test accounts, +rather than the publisher account, you will need to distribute +your public key to them. Developers without access to the publisher site do not +have access to your public key, and without the key they won't be able to +verify license responses.

    + +

    Note that if you decide to generate a new licensing key pair for your account +for some reason, you need to notify all users of test accounts. For +testers, you can embed the new key in the application package and distribute it +to users. For developers, you will need to distribute the new key to them +directly.

    + + +

    Signing in to an authorized account in the runtime +environment

    + +

    The licensing service is designed to determine whether a given user is +licensed to use a given application — during a license check, the Android +Market application gathers the user ID from the primary account on the system +and sends it to the server, together with the package name of the application +and other information. However, if there is no user information available, the +license check cannot succeed, so the Android Market application terminates the +request and returns an error to the application.

    + +

    During testing, to ensure that your application can successfully query the +licensing server, you must make sure that you sign in to an account on the +device or emulator using:

    + + + + + + +

    Signing in using a publisher account offers the advantage of letting your +applications receive static test responses even before the applications are +uploaded to the publisher site.

    + +

    If you are part of a larger organization or are working with external groups +on applications that will be published through your site, you will more likely +want to distribute test accounts instead, then use those to sign in during +testing.

    + +

    To sign in on a device or emulator, follow the steps below. The preferred +approach is to sign in as the primary account — however, if there are +other accounts already in use on the device or emulator, you can create an +additional account and sign in to it using the publisher or test account +credentials.

    + +
      +
    1. Open Settings > Accounts & sync
    2. +
    3. Select Add Account and choose to add a "Google" account. +
    4. +
    5. Select Next and then Sign in.
    6. +
    7. Enter the username and password of either the publisher account or a test +account that is registered in the publisher account.
    8. +
    9. Select Sign in. The system signs you in to the new +account.
    10. +
    + +

    Once you are signed in, you can begin testing licensing in your application +(if you have completed the LVL integration steps above). When your application +initiates a license check, it will receive a response containing the static test +response configured on the publisher account.

    + +

    Note that, if you are using an emulator, you will need to sign in to the +publisher account or test account each time you wipe data when restarting the +emulator.

    + +

    Once you've completed the setup procedures, continue to Adding Licensing to Your App.

    + + + diff --git a/docs/html/guide/publishing/licensing.html b/docs/html/guide/publishing/licensing.html new file mode 100644 index 000000000000..8e97f328da3c --- /dev/null +++ b/docs/html/guide/publishing/licensing.html @@ -0,0 +1,11 @@ + + + +Redirecting... + + +

    You should have been redirected. Please click here.

    + + \ No newline at end of file diff --git a/docs/html/guide/publishing/licensing.jd b/docs/html/guide/publishing/licensing.jd deleted file mode 100644 index 609241b7d0a2..000000000000 --- a/docs/html/guide/publishing/licensing.jd +++ /dev/null @@ -1,2388 +0,0 @@ -page.title=Application Licensing -@jd:body - -
    -
    - -

    Quickview

    -
      -
    • Licensing lets you protect your application on any device that includes Android Market.
    • -
    • Your app maintains control of how it enforces its licensing status.
    • -
    • Adding licensing to an app is straightforward, using the library available through the SDK.
    • -
    • The service is free and is available to all developers who publish on Android Market.
    • -
    - -

    In this document

    -
      -
    1. Setting Up A Publisher Account
    2. -
    3. Setting Up the Development Environment
    4. -
    5. Integrating the LVL with Your Application -
        -
      1. Including the LVL
      2. -
      3. Adding the licensing permission
      4. -
      5. Implementing a Policy
      6. -
      7. Implementing an Obfuscator
      8. -
      9. Checking the license
      10. -
      11. Implementing a DeviceLimiter
      12. -
    6. -
    7. Setting Up the Test Environment -
        -
      1. Test responses
      2. -
      3. Test accounts
      4. -
      5. Signing in on a device or emulator
      6. -
    8. -
    9. Obfuscating Your Application
    10. -
    11. Publishing a Licensed Application
    12. -
    13. Where to Get Support
    14. -
    - -

    Appendix

    -
      -
    1. Summary of LVL Classes and Interfaces
    2. -
    3. Server Response Codes
    4. -
    5. Server Response Extras
    6. -
    - -
    -
    - -

    Android Market offers a licensing service that lets you enforce licensing -policies for paid applications that you publish through Android Market. With -Android Market Licensing, your applications can query Android Market at run time to -obtain their licensing status for the current user, then allow or disallow -further use as appropriate.

    - -

    Using the service, you can apply a flexible licensing policy on an -application-by-application basis — each application can enforce licensing -in the way most appropriate for it. If necessary, an application can apply custom -constraints based on the licensing status obtained from Android Market. -For example, an application can check the licensing status and then apply custom -constraints that allow the user to run it unlicensed for a specific number -of times, or for a specific validity period. An application can also restrict use of the -application to a specific device, in addition to any other constraints.

    - -

    The licensing service is a secure means of controlling access to your -applications. When an application checks the licensing status, the Market server -signs the licensing status response using a key pair that is uniquely associated -with the publisher account. Your application stores the public key in its -compiled .apk file and uses it to verify the licensing status -response.

    - -

    Any application that you publish through Android Market can use the Android -Market Licensing service. No special account or registration is needed. -Additionally, because the service uses no dedicated framework APIs, you can add -licensing to any legacy application that uses a minimum API level of 3 or -higher.

    - -

    To help you add licensing to your application, the Android SDK provides -library sources that you can include in your application project. The -License Verification Library (LVL) handles all of -the licensing-related communication with the Android Market client and the -licensing service. With the LVL integrated, your application can determine its -licensing status for the current user by simply calling a library checker method -and implementing a callback that receives the status.

    - -

    This document explains how the licensing service works and how to add it to -your application.

    - - -

    Overview

    - -

    Android Market Licensing is a network-based service that lets an application -on an Android-powered device query a trusted licensing server, to determine -whether the application is licensed to the current device user. After receiving -the server response, the application can then allow or disallow further use of -the application as needed. In the service, the role of the licensing server is -to provide the license status for the current user; the application itself is -responsible for querying the server and conditionally granting access to the -application.

    - -

    Application, Android Market client, and server

    - -

    The licensing service is based on the capability of the Android Market server -to determine whether a given user is licensed to use a given application. The licensing server -considers a user to be licensed if the user is a recorded purchaser of an application. If a paid -application has been uploaded to Android Market but saved only as a draft application (in -other words, the app is unpublished), the licensing server considers all users to be licensed users -of the application. Keep in mind, you cannot implement Android Market Licensing in a free -application.

    - -

    To properly identify -the user and determine the license status, the server requires information about -the application and user — the application and the Android Market client -work together to assemble the information and pass it to the server.

    - -

    In the licensing service, an application does not query the licensing server -directly, but instead calls the Android Market client over remote IPC to -initiate a license request. In the license request:

    - - - -

    Notice that during a license check, the application does not manage any -network connections or use any licensing related APIs in the Android platform. -

    - -
    - -

    Figure 1. Your application initiates a -license check through the LVL and the Android Market -client, which handles communication with the Market server.

    -
    - -

    License responses secured through public key cryptography

    - -

    To ensure the integrity of each license query, the server signs the license -response data using an RSA key pair that is shared exclusively between the -server and the application publisher.

    - -

    The licensing service generates a single licensing key pair for each -publisher account and exposes the public key in the account's profile page. The -publisher copies the public key and embeds it in the application source code, -then compiles and publishes the .apk. The server retains the -private key internally and uses it to sign license responses for applications -published on that account.

    - -

    When the application receives a signed response, it uses the embedded public -key to verify the data. The use of public key cryptography in the licensing -service makes it possible for the application to detect responses that have been -tampered with or that are spoofed.

    - -

    Use of licensing in your application

    - -

    To use licensing in your application, add code to the application to -initiate a license check request and handle the response when it is received. -You can choose when, and how often, you want your application to check its -license and you have full control over how it handles the response, verifies the -signed response data, and enforces access controls.

    - -

    To simplify the process of adding support for licensing, download and -integrate the Licensing Verification Library, described below. Integration is -straightforward.

    - -

    When you are finished integrating the LVL, use a test environment -provided by the publisher site to test your application's handling of server -responses.

    - -

    Finally, publish the application .apk on Market using the -normal process. If you previously used the copy-protection provided by Android -Market, you can remove it from applications that use licensing.

    - -

    Licensing Verification Library simplifies implementation

    - -

    The Android SDK includes a License Verification Library (LVL) that you can -download and use as the basis for your application's licensing implementation. -The LVL greatly simplifies the process of adding licensing to your application -and helps ensure a more secure, robust implementation for your application. The -LVL provides internal classes that handle most of the standard operations of a -license query, such as contacting Android Market to initiate a license request -and verifying and validating the responses. It also exposes key interfaces that -let you easily plug in your custom code for defining licensing policy and -managing access as needed by your application. The key LVL interfaces are:

    - - - -

    To help you get started with a Policy, the LVL provides two fully complete -Policy implementations that you can use without modification or adapt to your -needs:

    - - - -

    The LVL is available as a downloadable component of the Android SDK. The -component includes both the LVL itself and an example application that shows how -the library should be integrated with your application and how your application -should manage response data, UI interaction, and error conditions.

    - -

    The LVL sources are provided as an Android library project, which -means that you can maintain a single set of library sources and share them -across multiple applications. A full test environment is also available through -the SDK, so you can develop and test the licensing implementation in your -applications before publishing them, even if you don't have access to a -physical device.

    - -

    Requirements and limitations

    - -

    Android Market Licensing is designed to let you apply license controls to -applications that you publish through Android Market. The service is not -designed to let you control access to applications that are not published -through Android Market or that are run on devices that do not offer the Android -Market client.

    - -

    Here are some points to keep in mind as you implement licensing in your -application:

    - - - -

    Replacement for Copy Protection

    - -

    Android Market Licensing is a flexible, secure mechanism for controlling -access to your applications. It effectively replaces the Copy Protection -mechanism offered on Android Market and gives you wider distribution -potential for your applications.

    - - - -

    Although no license mechanism can completely prevent all unauthorized use, -the licensing service lets you control access for most types of normal usage, -across all compatible devices, locked or unlocked, that run Android 1.5 or -higher version of the platform.

    - -

    The sections below describe how to add Android Market licensing to your -applications.

    - -

    Setting Up a Publisher Account

    - -

    Android Market licensing lets you manage access to applications that -users have downloaded from Android Market. To use licensing in an application, -you need to have a publisher account on Android Market so that you can -publish the application to users.

    - -

    If you don't already have a publisher account, you need to register for one -using your Google account and agree to the terms of service. Once you are -registered, you can upload applications at your convenience and begin debugging -and testing your licensing implementation. For more information about publishing -on Android Market, see Publishing Your -Applications

    - -

    To register as an Android Market developer and set up your publisher account, -visit the Android Market publisher site:

    - -

    http://market.android.com/publish -

    - -

    If you already have a publisher account on Android Market, use your existing -account to set up licensing. You do not need to register for a new -account to support licensing (and doing so is not recommended, especially if you -are adding licensing support to applications that you have already published). -In all cases, if you have published applications, you manage licensing for those -applications through the account on which the applications are published.

    - -

    Once your publisher account is set up, use the account to:

    - - - -

    Administrative settings for licensing

    - -

    Once you are signed into your publisher account, you can manage several -administrative controls for Android Market licensing. The controls are available -in the Edit Profile page, in the "Licensing" panel, shown below. The controls -let you:

    - - - -
    - - -
    Figure 2. The Licensing -panel of your account's Edit Profile page lets you manage administrative -settings for licensing.
    -
    - -

    For more information about how to work with test accounts and static test -responses, see Setting Up a Testing Environment, below. - -

    Setting Up the Development Environment

    - -

    Once you've set up your publisher account on Android Market, the next step is -to set up your development environment for licensing.

    - -

    Setting up your environment for licensing involves these tasks:

    - -
      -
    1. Downloading the latest SDK, if you haven't already done so
    2. -
    3. Setting up the runtime environment for development
    4. -
    5. Downloading the Market Licensing component into your SDK
    6. -
    7. Setting up the Licensing Verification Library
    8. -
    9. Including the LVL library project in your application
    10. -
    - -

    The sections below describe these tasks. When you are done with setup, -you can begin integrating the LVL into your applications.

    - -

    To get started, you need to set up a proper runtime environment on which -you can run, debug and test your application's implementation of license -checking and enforcement.

    - - -

    Downloading the latest SDK

    - - - -

    If you haven't done so, you need to download the Android SDK before you can -develop Android applications. The SDK provides the tools that you need to build -and debug Android applications, including applications that use Android Market -licensing. For complete information, including installation instructions, see -the Android SDK.

    - -

    If you have already installed the SDK, make sure to update the -SDK tools and ADT Plugin to the latest versions. You can update the SDK tools -using the Android SDK and AVD Manager and ADT through Help > -Software Updates... in Eclipse.

    - -

    After you've installed the latest SDK and tools, set up your development -environment as described below.

    - - -

    Setting up the runtime environment

    - -

    As described earlier, applications check licensing status not by contacting -the licensing server directly, but by binding to a service provided by the -Android Market application and initiating a license check request. The Android -Market service then handles the direct communication with the licensing server -and finally routes the response back to your application. To debug and test -licensing in your application, you need to set up a runtime environment that -includes the necessary Android Market service, so that your application is able -to send license check requests to the licensing server.

    - -

    There are two types of runtime environment that you can use:

    - - - -

    The sections below provide more information.

    - -

    Running on a device

    - -

    You can use an Android-powered device as the runtime environment for -debugging and testing licensing on your application.

    - -

    The device you use must:

    - - - -

    If Android Market is not preinstalled in the system image, your application won't -be able to communicate with the Android Market licensing server.

    - -

    For general information about how to set up a device for use in developing -Android applications, see Developing on a Device.

    - -

    Running on an Android emulator

    - -

    You can also use an Android emulator as your runtime -environment for debugging and testing licensing.

    - -

    Because the standard Android platforms provided in the Android SDK do -not include Android Market, you need to download the Google APIs Add-On -platform, API Level 8 (or higher), from the SDK repository. After downloading -the add-on, you need to create an AVD configuration that uses that system image. -

    - -

    The Google APIs Add-On does not include the full Android Market client. -However, it does provide:

    - - - -

    Several versions of the add-on are available in the SDK repository, but only -Google APIs Add-On, API 8 (release 2) or higher version of the -add-on includes the necessary Android Market services. This means that you -cannot use Google APIs Add-On API 7 or lower as a runtime environment for -developing licensing on an emulator.

    - -
    - - -
    Figure 3. Google APIs -Add-On, API 8 (release 2) or higher lets you debug and test your licensing -implementation in an emulator.
    -
    - -

    To set up an emulator for adding licensing to an application, follow -these steps:

    - -
      -
    1. Launch the Android SDK and AVD Manager.
    2. -
    3. In the Available Packages panel, select and download the -SDK component "Google APIs (Google Inc.) - API Level 8" (or higher) from the SDK -repository, as shown in the figure above. -

      When the download is complete, use the Android SDK and AVD Manager to -create a new AVD based on that component, described next.

    4. -
    5. In the Virtual -Devices panel of the Android SDK and AVD Manager, click -New and set the configuration details for the new AVD.
    6. -
    7. In the dialog that appears, assign a descriptive name to the AVD and then -use the "Target" menu to choose the "Google APIs (Google Inc.) - API Level 8" as -the system image to run on the new AVD. Set the other configuration details as -needed and then click Create AVD to finish. The SDK tools -create the new AVD configuration, which then appears in the list of available -Android Virtual Devices.
    8. -
    - -

    If you are not familiar with AVDs or how to use them, see Managing Virtual Devices.

    - -

    Updating your project configuration

    - -

    After you set up a runtime environment that meets the requirements described -above — either on an actual device or on an emulator — make sure to -update your application project or build scripts as needed, so that your compiled -.apk files that use licensing are deployed into that environment. -In particular, if you are developing in Eclipse, make sure that you set up a -Run/Debug Configuration that targets the appropriate device or AVD.

    - -

    You do not need to make any changes to your application's -build configuration, provided that the project is already configured to compile -against a standard Android 1.5 (API level 3) or higher library. For example: - -

    - -

    In general, adding licensing to an application should have no impact -whatsoever on the application's build configuration.

    - - -

    Downloading the LVL

    - -

    The License Verification Library (LVL) is a collection of helper classes that -greatly simplify the work that you need to do to add licensing to your -application. In all cases, we recommend that you download the LVL and use it as -the basis for the licensing implementation in your application.

    - -

    The LVL is available as a downloadable component of the Android SDK. The -component includes:

    - - - -

    To download the LVL component into your development environment, use the -Android SDK and AVD Manager. Launch the Android SDK and AVD Manager and then -select the "Market Licensing" component, as shown in the figure below. -Accept the terms and click Install Selected to begin the download.

    - -
    - - -
    Figure 4. The Market -Licensing package contains the LVL and the LVL sample application.
    -
    - -

    When the download is complete, the Android SDK and AVD Manager installs both -the LVL library project and the example application into these directories:

    - -

    <sdk>/extras/google/market_licensing/library/ -  (the LVL library project)
    -<sdk>/extras/google/market_licensing/sample/  (the example -application)

    - -

    If you aren't familiar with how to download components into your SDK, see the -Adding SDK Components -document.

    - - -

    Setting Up the Licensing Verification Library

    - -

    After downloading the LVL to your computer, you need to set it up in your -development environment, either as an Android library project or by -copying (or importing) the library sources directly into your existing -application package. In general, using the LVL as a library project is recommended, -since it lets you reuse your licensing code across multiple applications and -maintain it more easily over time. Note that the LVL is not designed to be -compiled separately and added to an application as a static .jar file.

    - -

    Moving the library sources to a new location

    - -

    Because you will be customizing the LVL sources to some extent, you should -make sure to move or copy the library sources (the entire -directory at <sdk>/market_licensing/library/) -to a working directory outside of the SDK. You should then use the relocated -sources as your working set. If you are using a source-code management -system, add and track the sources that are in the working location rather -than those in default location in the SDK.

    - -

    Moving the library sources is important is because, when you later update the -Market licensing package, the SDK installs the new files to the same location as -the older files. Moving your working library files to a safe location ensures -that your work won't be inadvertently overwritten should you download a new -version of the LVL.

    - -

    Creating the LVL as a library project

    - - - -

    The recommended way of using the LVL is setting it up as a new Android -library project. A library project is a type of development project -that holds shared Android source code and resources. Other Android application -projects can reference the library project and, at build time, include its -compiled sources in their .apk files. In the context of licensing, -this means that you can do most of your licensing development once, in a library -project, then include the library sources in your various application projects. -In this way, you can easily maintain a uniform implementation of licensing -across all of your projects and maintain it centrally.

    - -

    The LVL is provided as a configured library project — once you have -downloaded it, you can start using it right away.

    - -

    If you are working in Eclipse with ADT, you need to add the LVL to your -workspace as a new development project, in the same way as you would a new -application project.

    - -
      -
    1. Use the New Project Wizard to create a new -project from existing sources. Select the LVL's library directory -(the directory containing the library's AndroidManifest.xml file) as the project -root.
    2. -
    3. When you are creating the library project, you can select any application -name, package, and set other fields as needed.
    4. -
    5. For the library's build target, select Android 1.5 (API level 3) or higher.
    6. -
    - -

    When created, the project is -predefined as a library project in its project.properties file, so -no further configuration is needed.

    - -

    For more information about how to create an application project or work with -library projects in Eclipse, see Managing Projects from -Eclipse with ADT

    . - -

    Copying the LVL sources to your application

    - -

    As an alternative to adding the LVL as a library project, you can copy the -library sources directly into your application. To do so, copy (or import) the -LVL's library/src/com directory into your application's -src/ directory.

    - -

    If you add the LVL sources directly to your application, you can skip the -next section and start working with the library, as described in .

    - - -

    Including the LVL library project sources in your -application

    - -

    If you want to use the LVL sources as a library project, you need to add a -reference to the LVL library project in your application project properties. This tells -build tools to include the LVL library project sources in your application at -compile time. The process for adding a reference to a library project depends -on your development environment, as described below.

    - -

    If you are developing in Eclipse with ADT, you should already have added the -library project to your workspace, as described in the previous section. If you -haven't done that already, do it now before continuing.

    - -

    Next, open the application's project properties window, as shown below. -Select the "Android" properties group and click Add, then -choose the LVL library project (com_android_vending_licensing) and click -OK. For more information, see - -Managing Projects from Eclipse with ADT

    . - -
    - - -
    Figure 5. If you are -working in Eclipse with ADT, you can add the LVL library project to your -application from the application's project properties.
    -
    - -

    If you are developing using the SDK command-line tools, navigate to the -directory containing your application project and open the -project.properties file. Add a line to the file that specifies the -android.library.reference.<n> key and the path to the -library. For example:

    - -
    android.library.reference.1=path/to/library_project
    - -

    Alternatively, you can use this command to update the project -properties, including the reference to the library project:

    - -
    android update lib-project
    ---target <target_ID> \
    ---path path/to/my/app_project \
    ---library path/to/my/library_project
    -
    - -

    For more information about working with library projects, -see -Managing Projects from the Command Line

    . - - -

    Integrating the LVL with Your Application

    - -

    Once you've followed the steps above to set up a publisher account and -development environment, you are ready to begin integrating the LVL with your -application.

    - -

    Integrating the LVL with your application code involves these tasks:

    - -
      -
    1. Adding the licensing permission your application's manifest.
    2. -
    3. Implementing a Policy — you can choose one of the full implementations provided in the LVL or create your own.
    4. -
    5. Implementing an Obfuscator, if your Policy will cache any license response data.
    6. -
    7. Adding code to check the license in your application's main Activity
    8. -
    9. Implementing a DeviceLimiter (optional and not recommended for most applications)
    10. -
    - -

    The sections below describe these tasks. When you are done with the -integration, you should be able to compile your application successfully and you -can begin testing, as described in Setting Up the Test -Environment.

    - -

    For an overview of the full set of source files included in the LVL, see Summary of LVL Classes and Interfaces.

    - - -

    Adding the licensing permission to your -AndroidManifest.xml

    - -

    To use the Android Market application for sending a license check to the -server, your application must request the proper permission, -com.android.vending.CHECK_LICENSE. If your application does -not declare the licensing permission but attempts to initiate a license check, -the LVL throws a security exception.

    - -

    To request the licensing permission in your application, declare a <uses-permission> -element as a child of <manifest>, as follows:

    - -

    <uses-permission -android:name="com.android.vending.CHECK_LICENSE">

    - -

    For example, here's how the LVL sample application declares the permission: -

    - -
    <?xml version="1.0" encoding="utf-8"?>
    -
    -<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...">
    -    <!-- Devices >= 3 have version of Android Market that supports licensing. -->
    -    <uses-sdk android:minSdkVersion="3" />
    -    <!-- Required permission to check licensing. -->
    -    <uses-permission android:name="com.android.vending.CHECK_LICENSE" />
    -    ...
    -</manifest>
    -
    - -

    Note: Currently, you cannot declare the -CHECK_LICENSE permission in the LVL library project's manifest, -because the SDK Tools will not merge it into the manifests of dependent -applications. Instead, you must declare the permission in each dependent -application's manifest.

    - - -

    Implementing a Policy

    - - - -

    Android Market licensing service does not itself determine whether a -given user with a given license should be granted access to your application. -Rather, that responsibility is left to a Policy implementation that you provide -in your application.

    - -

    Policy is an interface declared by the LVL that is designed to hold your -application's logic for allowing or disallowing user access, based on the result -of a license check. To use the LVL, your application must provide an -implementation of Policy.

    - -

    The Policy interface declares two methods, allowAccess() and -processServerResponse(), which are called by a LicenseChecker -instance when processing a response from the license server. It also declares an -enum called LicenseResponse, which specifies the license response -value passed in calls to processServerResponse().

    - - - -

    To simplify the process of adding licensing to your application and to -provide an illustration of how a Policy should be designed, the LVL includes -two full Policy implementations that you can use without modification or -adapt to your needs:

    - - - -

    For most applications, the use of ServerManagedPolicy is highly -recommended. ServerManagedPolicy is the LVL default and is integrated with -the LVL sample application.

    - - -

    Guidelines for custom policies

    - -

    In your licensing implementation, you can use one of the complete policies -provided in the LVL (ServerManagedPolicy or StrictPolicy) or you can create a -custom policy. For any type of custom policy, there are several important design -points to understand and account for in your implementation.

    - -

    The licensing server applies general request limits to guard against overuse -of resources that could result in denial of service. When an application exceeds -the request limit, the licensing server returns a 503 response, which gets -passed through to your application as a general server error. This means that no -license response will be available to the user until the limit is reset, which -can affect the user for an indefinite period.

    - -

    If you are designing a custom policy, we recommend that the Policy: -

      - -
    1. Caches (and properly obfuscates) the most recent successful license response -in local persistent storage.
    2. -
    3. Returns the cached response for all license checks, for as long as the -cached response is valid, rather than making a request to the licensing server. -Setting the response validity according to the server-provided VT -extra is highly recommended. See Server Response Extras -for more information.
    4. -
    5. Uses an exponential backoff period, if retrying any requests the result in -errors. Note that the Android Market client automatically retries failed -requests, so in most cases there is no need for your Policy to retry them.
    6. -
    7. Provides for a "grace period" that allows the user to access your -application for a limited time or number of uses, while a license check is being -retried. The grace period benefits the user by allowing access until the next -license check can be completed successfully and it benefits you by placing a -hard limit on access to your application when there is no valid license response -available.
    8. -
    - -

    Designing your Policy according to the guidelines listed above is critical, -because it ensures the best possible experience for users while giving you -effective control over your application even in error conditions.

    - -

    Note that any Policy can use settings provided by the licensing server to -help manage validity and caching, retry grace period, and more. Extracting the -server-provided settings is straightforward and making use of them is highly -recommended. See the ServerManagedPolicy implementation for an example of how to -extract and use the extras. For a list of server settings and information about -how to use them, see Server Response Extras in the -Appendix of this document.

    - -

    ServerManagedPolicy

    - - - -

    The LVL includes a full and recommended implementation of the Policy -interface called ServerManagedPolicy. The implementation is integrated with the -LVL classes and serves as the default Policy in the library.

    - -

    ServerManagedPolicy provides all of the handling for license and retry -responses. It caches all of the response data locally in a -{@link android.content.SharedPreferences} file, obfuscating it with the -application's Obfuscator implementation. This ensures that the license response -data is secure and persists across device power cycles. ServerManagedPolicy -provides concrete implementations of the interface methods -processServerResponse() and allowAccess() and also -includes a set of supporting methods and types for managing license -responses.

    - -

    Importantly, a key feature of ServerMangedPolicy is its use of -server-provided settings as the basis for managing licensing across an -application's refund period and through varying network and error conditions. -When an application contacts the Android Market server for a license check, the -server appends several settings as key-value pairs in the extras field of certain -license response types. For example, the server provides recommended values for the -application's license validity period, retry grace period, and maximum allowable -retry count, among others. ServerManagedPolicy extracts the values from the -license response in its processServerResponse() method and checks -them in its allowAccess() method. For a list of the server-provided -settings used by ServerManagedPolicy, see Server Response -Extras in the Appendix of this document.

    - -

    For convenience, best performance, and the benefit of using license settings -from the Android Market server, using ServerManagedPolicy as your -licensing Policy is strongly recommended.

    - -

    If you are concerned about the security of license response data that is -stored locally in SharedPreferences, you can use a stronger obfuscation -algorithm or design a stricter Policy that does not store license data. The LVL -includes an example of such a Policy — see StrictPolicy for more information.

    - -

    To use ServerManagedPolicy, simply import it to your Activity, create an -instance, and pass a reference to the instance when constructing your -LicenseChecker. See Instantiate LicenseChecker and -LicenseCheckerCallback for more information.

    - -

    StrictPolicy

    - -

    The LVL includes an alternative full implementation of the Policy interface -called StrictPolicy. The StrictPolicy implementation provides a more restrictive -Policy than ServerManagedPolicy, in that it does not allow the user to access -the application unless a license response is received from the server at the -time of access that indicates that the user is licensed.

    - -

    The principal feature of StrictPolicy is that it does not store any -license response data locally, in a persistent store. Because no data is stored, -retry requests are not tracked and cached responses can not be used to fulfill -license checks. The Policy allows access only if:

    - - - -

    Using StrictPolicy is appropriate if your primary concern is to ensure that, -in all possible cases, no user will be allowed to access the application unless -the user is confirmed to be licensed at the time of use. Additionally, the -Policy offers slightly more security than ServerManagedPolicy — since -there is no data cached locally, there is no way a malicious user could tamper -with the cached data and obtain access to the application.

    - -

    At the same time, this Policy presents a challenge for normal users, since it -means that they won't be able to access the application when there is no network -(cell or wi-fi) connection available. Another side-effect is that your -application will send more license check requests to the server, since using a -cached response is not possible.

    - -

    Overall, this policy represents a tradeoff of some degree of user convenience -for absolute security and control over access. Consider the tradeoff carefully -before using this Policy.

    - -

    To use StrictPolicy, simply import it to your Activity, create an instance, -and pass a reference to it when constructing your LicenseChecker. See -Instantiate LicenseChecker and LicenseCheckerCallback -for more information.

    - -

    Implementing an Obfuscator

    - - - -

    A typical Policy implementation needs to save the license response data for -an application to a persistent store, so that it is accessible across -application invocations and device power cycles. For example, a Policy would -maintain the timestamp of the last successful license check, the retry count, -the license validity period, and similar information in a persistent store, -rather than resetting the values each time the application is launched. The -default Policy included in the LVL, ServerManagedPolicy, stores license response -data in a {@link android.content.SharedPreferences} instance, to ensure that the -data is persistent.

    - -

    Because the Policy will use stored license response data to determine whether -to allow or disallow access to the application, it must ensure that any -stored data is secure and cannot be reused or manipulated by a root user on a -device. Specifically, the Policy must always obfuscate the data before storing -it, using a key that is unique for the application and device. Obfuscating using -a key that is both application-specific and device-specific is critical, because -it prevents the obfuscated data from being shared among applications and -devices.

    - -

    The LVL assists the application with storing its license response data in a -secure, persistent manner. First, it provides an Obfuscator -interface that lets your application supply the obfuscation algorithm of its -choice for stored data. Building on that, the LVL provides the helper class -PreferenceObfuscator, which handles most of the work of calling the -application's Obfuscator class and reading and writing the obfuscated data in a -SharedPreferences instance.

    - -

    The LVL provides a full Obfuscator implementation called -AESObfuscator that uses AES encryption to obfuscate data. You can -use AESObfuscator in your application without modification or you -can adapt it to your needs. For more information, see the next section.

    - - -

    AESObfuscator

    - -

    The LVL includes a full and recommended implementation of the Obfuscator -interface called AESObfuscator. The implementation is integrated with the -LVL sample application and serves as the default Obfuscator in the library.

    - -

    AESObfuscator provides secure obfuscation of data by using AES to -encrypt and decrypt the data as it is written to or read from storage. -The Obfuscator seeds the encryption using three data fields provided -by the application:

    - -
      -
    1. A salt — an array of random bytes to use for each (un)obfuscation.
    2. -
    3. An application identifier string, typically the package name of the application.
    4. -
    5. A device identifier string, derived from as many device-specific sources -as possible, so as to make it as unique.
    6. -
    - -

    To use AESObfuscator, first import it to your Activity. Declare a private -static final array to hold the salt bytes and initialize it to 20 randomly -generated bytes.

    - -
        ...
    -    // Generate 20 random bytes, and put them here.
    -    private static final byte[] SALT = new byte[] {
    -     -46, 65, 30, -128, -103, -57, 74, -64, 51, 88, -95,
    -     -45, 77, -117, -36, -113, -11, 32, -64, 89
    -     };
    -    ...
    -
    - -

    Next, declare a variable to hold a device identifier and generate a value for -it in any way needed. For example, the sample application included in the LVL -queries the system settings for the -android.Settings.Secure.ANDROID_ID, which is unique to each device. -

    - -

    Note that, depending on the APIs you use, your application might need to -request additional permissions in order to acquire device-specific information. -For example, to query the {@link android.telephony.TelephonyManager} to obtain -the device IMEI or related data, the application will also need to request the -android.permission.READ_PHONE_STATE permission in its manifest.

    - -

    Before requesting new permissions for the sole purpose of acquiring -device-specific information for use in your Obfuscator, consider -how doing so might affect your application or its filtering on Android Market -(since some permissions can cause the SDK build tools to add -the associated <uses-feature>).

    - -

    Finally, construct an instance of AESObfuscator, passing the salt, -application identifier, and device identifier. You can construct the instance -directly, while constructing your Policy and LicenseChecker. For example:

    - -
        ...
    -    // Construct the LicenseChecker with a Policy.
    -    mChecker = new LicenseChecker(
    -        this, new ServerManagedPolicy(this,
    -            new AESObfuscator(SALT, getPackageName(), deviceId)),
    -        BASE64_PUBLIC_KEY  // Your public licensing key.
    -        );
    -    ...
    -
    - -

    For a complete example, see MainActivity in the LVL sample application.

    - - -

    Checking the license from your application's main Activity

    - -

    Once you've implemented a Policy for managing access to your application, the -next step is to add a license check to your application, which initiates a query -to the licensing server if needed and manages access to the application based on -the license response. All of the work of adding the license check and handling -the response takes place in your main {@link android.app.Activity} source file. -

    - -

    To add the license check and handle the response, you must:

    - -
      -
    1. Add imports
    2. -
    3. Implement LicenseCheckerCallback as a private inner class
    4. -
    5. Create a Handler for posting from LicenseCheckerCallback to the UI thread
    6. -
    7. Instantiate LicenseChecker and LicenseCheckerCallback
    8. -
    9. Call checkAccess() to initiate the license check
    10. -
    11. Embed your public key for licensing
    12. -
    13. Call your LicenseChecker's onDestroy() method to close IPC connections.
    14. -
    - -

    The sections below describe these tasks.

    - -

    Overview of license check and response

    - - - -

    In most cases, you should add the license check to your application's main -{@link android.app.Activity}, in the onCreate() method. This -ensures that when the user launches your application directly, the license check -will be invoked immediately. In some cases, you can add license checks in other -locations as well. For example, if your application includes multiple Activity -components that other applications can start by {@link android.content.Intent}, -you could add license checks in those Activities.

    - -

    A license check consists of two main actions:

    - - - -
    - - -
    Figure 6. Overview of a -typical license check interaction.
    -
    - -

    The diagram above illustrates how a typical license check takes place:

    - -
      -
    1. Code in the application's main Activity instantiates LicenseCheckerCallback -and LicenseChecker objects. When constructing LicenseChecker, the code passes in -{@link android.content.Context}, a Policy implementation to use, and the -publisher account's public key for licensing as parameters.
    2. -
    3. The code then calls the checkAccess() method on the -LicenseChecker object. The method implementation calls the Policy to determine -whether there is a valid license response cached locally, in -{@link android.content.SharedPreferences}. -
        -
      • If so, the checkAccess() implementation calls -allow().
      • -
      • Otherwise, the LicenseChecker initiates a license check request that is sent -to the licensing server.
      • -
      -

      Note: The licensing server always returns -LICENSED when you perform a license check of a draft application.

      -
    4. -
    5. When a response is received, LicenseChecker creates a LicenseValidator that -verifies the signed license data and extracts the fields of the response, then -passes them to your Policy for further evaluation. -
        -
      • If the license is valid, the Policy caches the response in -SharedPreferences and notifies the validator, which then calls the -allow() method on the LicenseCheckerCallback object.
      • -
      • If the license not valid, the Policy notifies the validator, which calls -the dontAllow() method on LicenseCheckerCallback.
      • -
      -
    6. -
    7. In case of a recoverable local or server error, such as when the network is -not available to send the request, LicenseChecker passes a RETRY response to -your Policy's processServerResponse() method.
    8. -
    9. In case of a application error, such as when the application attempts to -check the license of an invalid package name, LicenseChecker passes an error -response to the LicenseCheckerCallback's applicationError() -method.
    10. -
    - -

    Note that, in addition to initiating the license check and handling the -result, which are described in the sections below, your application also needs -to provide a Policy implementation and, if the Policy -stores response data (such as ServerManagedPolicy), an Obfuscator implementation.

    - - -

    Add imports

    - -

    First, open the class file of the application's main Activity and import -LicenseChecker and LicenseCheckerCallback from the LVL package.

    - -
        import com.android.vending.licensing.LicenseChecker;
    -    import com.android.vending.licensing.LicenseCheckerCallback;
    - -

    If you are using the default Policy implementation provided with the LVL, -ServerManagedPolicy, import it also, together with the AESObfuscator. If you are -using a custom Policy or Obfuscator, import those instead.

    - -
        import com.android.vending.licensing.ServerManagedPolicy;
    -    import com.android.vending.licensing.AESObfuscator;
    - -

    Implement LicenseCheckerCallback as a private inner class

    - -

    LicenseCheckerCallback is an interface provided by the LVL for handling -result of a license check. To support licensing using the LVL, you must -implement LicenseCheckerCallback and -its methods to allow or disallow access to the application.

    - -

    The result of a license check is always a call to one of the -LicenseCheckerCallback methods, made based on the validation of the response -payload, the server response code itself, and any additional processing provided -by your Policy. Your application can implement the methods in any way needed. In -general, it's best to keep the methods simple, limiting them to managing UI -state and application access. If you want to add further processing of license -responses, such as by contacting a backend server or applying custom constraints, -you should consider incorporating that code into your Policy, rather than -putting it in the LicenseCheckerCallback methods.

    - -

    In most cases, you should declare your implementation of -LicenseCheckerCallback as a private class inside your application's main -Activity class.

    - -

    Implement the allow() and dontAllow() methods as -needed. To start with, you can use simple result-handling behaviors in the -methods, such as displaying the license result in a dialog. This helps you get -your application running sooner and can assist with debugging. Later, after you -have determined the exact behaviors you want, you can add more complex handling. -

    - -

    Some suggestions for handling unlicensed responses in -dontAllow() include:

    - - - -

    The example below shows how the LVL sample application implements -LicenseCheckerCallback, with methods that display the license check result in a -dialog.

    - -
        private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
    -        public void allow() {
    -            if (isFinishing()) {
    -                // Don't update UI if Activity is finishing.
    -                return;
    -            }
    -            // Should allow user access.
    -            displayResult(getString(R.string.allow));
    -        }
    -
    -        public void dontAllow() {
    -            if (isFinishing()) {
    -                // Don't update UI if Activity is finishing.
    -                return;
    -            }
    -            displayResult(getString(R.string.dont_allow));
    -            // Should not allow access. An app can handle as needed,
    -            // typically by informing the user that the app is not licensed
    -            // and then shutting down the app or limiting the user to a
    -            // restricted set of features.
    -            // In this example, we show a dialog that takes the user to Market.
    -            showDialog(0);
    -        }
    -    }
    -
    - -

    Additionally, you should implement the applicationError() -method, which the LVL calls to let your application handle errors that are not -retryable. For a list of such errors, see Server Response Codes in the Appendix of this -document. You can implement the method in any way needed. In most cases, the -method should log the error code and call dontAllow().

    - -

    Create a Handler for posting from LicenseCheckerCallback -to the UI thread

    - -

    During a license check, the LVL passes the request to the Android Market -application, which handles communication with the licensing server. The LVL -passes the request over asynchronous IPC (using {@link android.os.Binder}) so -the actual processing and network communication do not take place on a thread -managed by your application. Similarly, when the Android Market application -receives the result, it invokes a callback method over IPC, which in turn -executes in an IPC thread pool in your application's process.

    - -

    The LicenseChecker class manages your application's IPC communication with -the Android Market application, including the call that sends the request and -the callback that receives the response. LicenseChecker also tracks open license -requests and manages their timeouts.

    - -

    So that it can handle timeouts properly and also process incoming responses -without affecting your application's UI thread, LicenseChecker spawns a -background thread at instantiation. In the thread it does all processing of -license check results, whether the result is a response received from the server -or a timeout error. At the conclusion of processing, the LVL calls your -LicenseCheckerCallback methods from the background thread.

    - -

    To your application, this means that:

    - -
      -
    1. Your LicenseCheckerCallback methods will be invoked, in many cases, from a -background thread.
    2. -
    3. Those methods won't be able to update state or invoke any processing in the -UI thread, unless you create a Handler in the UI thread and have your callback -methods post to the Handler.
    4. -
    - -

    If you want your LicenseCheckerCallback methods to update the UI thread, -instantiate a {@link android.os.Handler} in the main Activity's -{@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method, -as shown below. In this example, the LVL sample application's -LicenseCheckerCallback methods (see above) call displayResult() to -update the UI thread through the Handler's -{@link android.os.Handler#post(java.lang.Runnable) post()} method.

    - -
    private Handler mHandler;
    -
    -    @Override
    -    public void onCreate(Bundle savedInstanceState) {
    -        ...
    -        mHandler = new Handler();
    -    }
    -
    - -

    Then, in your LicenseCheckerCallback methods, you can use Handler methods to -post Runnable or Message objects to the Handler. Here's how the sample -application included in the LVL posts a Runnable to a Handler in the UI thread -to display the license status.

    - -
        private void displayResult(final String result) {
    -        mHandler.post(new Runnable() {
    -            public void run() {
    -                mStatusText.setText(result);
    -                setProgressBarIndeterminateVisibility(false);
    -                mCheckLicenseButton.setEnabled(true);
    -            }
    -        });
    -    }
    -
    - -

    Instantiate LicenseChecker and LicenseCheckerCallback

    - -

    In the main Activity's -{@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method, -create private instances of LicenseCheckerCallback and LicenseChecker. You must -instantiate LicenseCheckerCallback first, because you need to pass a reference -to that instance when you call the contructor for LicenseChecker.

    - -

    When you instantiate LicenseChecker, you need to pass in these parameters:

    - - - -

    If you are using ServerManagedPolicy, you won't need to access the class -directly, so you can instantiate it in the LicenseChecker constructor, -as shown in the example below. Note that you need to pass a reference to a new -Obfuscator instance when you construct ServerManagedPolicy.

    - -

    The example below shows the instantiation of LicenseChecker and -LicenseCheckerCallback from the onCreate() method of an Activity -class.

    - -
    public class MainActivity extends Activity {
    -    ...
    -    private LicenseCheckerCallback mLicenseCheckerCallback;
    -    private LicenseChecker mChecker;
    -
    -    @Override
    -    public void onCreate(Bundle savedInstanceState) {
    -        super.onCreate(savedInstanceState);
    -        ...
    -        // Construct the LicenseCheckerCallback. The library calls this when done.
    -        mLicenseCheckerCallback = new MyLicenseCheckerCallback();
    -
    -        // Construct the LicenseChecker with a Policy.
    -        mChecker = new LicenseChecker(
    -            this, new ServerManagedPolicy(this,
    -                new AESObfuscator(SALT, getPackageName(), deviceId)),
    -            BASE64_PUBLIC_KEY  // Your public licensing key.
    -            );
    -        ...
    -    }
    -}
    -
    - - -

    Note that LicenseChecker calls the LicenseCheckerCallback methods from the UI -thread only if there is valid license response cached locally. If the -license check is sent to the server, the callbacks always originate from the -background thread, even for network errors.

    - - -

    Call checkAccess() to initiate the license check

    - -

    In your main Activity, add a call to the checkAccess() method of the -LicenseChecker instance. In the call, pass a reference to your -LicenseCheckerCallback instance as a parameter. If you need to handle any -special UI effects or state management before the call, you might find it useful -to call checkAccess() from a wrapper method. For example, the LVL -sample application calls checkAccess() from a -doCheck() wrapper method:

    - -
        @Override
    -    public void onCreate(Bundle savedInstanceState) {
    -        super.onCreate(savedInstanceState);
    -        ...
    -        // Call a wrapper method that initiates the license check
    -        doCheck();
    -        ...
    -    }
    -    ...
    -    private void doCheck() {
    -        mCheckLicenseButton.setEnabled(false);
    -        setProgressBarIndeterminateVisibility(true);
    -        mStatusText.setText(R.string.checking_license);
    -        mChecker.checkAccess(mLicenseCheckerCallback);
    -    }
    -
    - - -

    Embed your public key for licensing

    - -

    For each publisher account, the Android Market service automatically -generates a 2048-bit RSA public/private key pair that is used exclusively for -licensing. The key pair is uniquely associated with the publisher account and is -shared across all applications that are published through the account. Although -associated with a publisher account, the key pair is not the same as -the key that you use to sign your applications (or derived from it).

    - -

    The Android Market publisher site exposes the public key for licensing to any -developer signed in to the publisher account, but it keeps the private key -hidden from all users in a secure location. When an application requests a -license check for an application published in your account, the licensing server -signs the license response using the private key of your account's key pair. -When the LVL receives the response, it uses the public key provided by the -application to verify the signature of the license response.

    - -

    To add licensing to an application, you must obtain your publisher account's -public key for licensing and copy it into your application. Here's how to find -your account's public key for licensing:

    - -
      -
    1. Go to the Android Market publisher site and sign in. -Make sure that you sign in to the account from which the application you are -licensing is published (or will be published).
    2. -
    3. In the account home page, locate the "Edit profile" link and click it.
    4. -
    5. In the Edit Profile page, locate the "Licensing" pane, shown below. Your -public key for licensing is given in the "Public key" text box.
    6. -
    - -

    To add the public key to your application, simply copy/paste the key string -from the text box into your application as the value of the String variable -BASE64_PUBLIC_KEY. When you are copying, make sure that you have -selected the entire key string, without omitting any characters.

    - -

    Here's an example from the LVL sample application:

    - -
        public class MainActivity extends Activity {
    -        private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG ... "; //truncated for this example
    -    ...
    -    }
    -
    - -

    Call your LicenseChecker's onDestroy() method -to close IPC connections

    - -

    Finally, to let the LVL clean up before your application -{@link android.content.Context} changes, add a call to the LicenseChecker's -onDestroy() method from your Activity's -{@link android.app.Activity#onDestroy()} implementation. The call causes the -LicenseChecker to properly close any open IPC connection to the Android Market -application's ILicensingService and removes any local references to the service -and handler.

    - -

    Failing to call the LicenseChecker's onDestroy() method -can lead to problems over the lifecycle of your application. For example, if the -user changes screen orientation while a license check is active, the application -{@link android.content.Context} is destroyed. If your application does not -properly close the LicenseChecker's IPC connection, your application will crash -when the response is received. Similarly, if the user exits your application -while a license check is in progress, your application will crash when the -response is received, unless it has properly called the -LicenseChecker's onDestroy() method to disconnect from the service. -

    - -

    Here's an example from the sample application included in the LVL, where -mChecker is the LicenseChecker instance:

    - -
        @Override
    -    protected void onDestroy() {
    -        super.onDestroy();
    -        mChecker.onDestroy();
    -        ...
    -    }
    -
    - -

    If you are extending or modifying LicenseChecker, you might also need to call -the LicenseChecker's finishCheck() method, to clean up any open IPC -connections.

    - -

    Implementing a DeviceLimiter

    - -

    In some cases, you might want your Policy to limit the number of actual -devices that are permitted to use a single license. This would prevent a user -from moving a licensed application onto a number of devices and using the -application on those devices under the same account ID. It would also prevent a -user from "sharing" the application by providing the account information -associated with the license to other individuals, who could then sign in to that -account on their devices and access the license to the application.

    - -

    The LVL supports per-device licensing by providing a -DeviceLimiter interface, which declares a single method, -allowDeviceAccess(). When a LicenseValidator is handling a response -from the licensing server, it calls allowDeviceAccess(), passing a -user ID string extracted from the response.

    - -

    If you do not want to support device limitation, no work is -required — the LicenseChecker class automatically uses a default -implementation called NullDeviceLimiter. As the name suggests, NullDeviceLimiter -is a "no-op" class whose allowDeviceAccess() method simply returns -a LICENSED response for all users and devices.

    - -
    -

    Caution: Per-device licensing is not recommended for -most applications because:

    - -
    - - -

    Setting Up the Testing Environment

    - -

    The Android Market publisher site provides configuration tools that let you -and others test licensing on your application before it is published. As you are -implementing licensing, you can make use of the publisher site tools to test -your application's Policy and handling of different licensing responses and -error conditions.

    - -

    The main components of the test environment for licensing include:

    - - - -

    Setting up the test environment properly involves:

    - -
      -
    1. Setting static test responses that are returned by the licensing server.
    2. -
    3. Setting up test accounts as needed.
    4. -
    5. Signing in properly to an emulator or device, before initiating a license check test.
    6. -
    - -

    The sections below provide more information.

    - - -

    Setting test responses for license checks

    - -

    Android Market provides a configuration setting in your publisher account -that lets you override the normal processing of a license check and return a -specified static response code. The setting is for testing only and applies -only to license checks for applications that you have uploaded, made by -any user signed in to an emulator or device using the credentials of the -publisher account or a registered test account. For other users, the server -always processes license checks according to normal rules.

    - -

    To set a test response for your account, sign in to your publisher account -and click "Edit Profile". In the Edit Profile page, locate the Test Response -menu in the Licensing panel, shown below. You can select from the full set of -valid server response codes to control the response or condition you want to -test in your application.

    - -

    In general, you should make sure to test your application's licensing -implementation with every response code available in the Test Response menu. -For a description of the codes, see Server -Response Codes in the Appendix of this document.

    - -
    - - -
    Figure 7. The Licensing -panel of your account's Edit Profile page, showing the Test Accounts field and the -Test Response menu.
    -
    - -

    Note that the test response that you configure applies account-wide — -that is, it applies not to a single application, but to all -applications associated with the publisher account. If you are testing multiple -applications at once, changing the test response will affect all of those -applications on their next license check (if the user is signed into -the emulator or device using the publisher account or a test account).

    - -

    Before you can successfully receive a test response for a license check, -you must sign in to the device or emulator on which the application -is installed, and from which it is querying the server. Specifically, you must -sign using either your publisher account or one of the test accounts that you -have set up. For more information about test accounts, see the next section.

    - -

    See Server Response Codes for a list of -test responses available and their meanings.

    - - -

    Setting up test accounts

    - -

    In some cases, you might want to let multiple teams of developers test -licensing on applications that will ultimately be published through your -publisher account, but without giving them access to your publisher account's -sign-in credentials. To meet that need, the Android Market publisher site lets -you set up one or more optional test accounts — accounts that are -authorized to query the licensing server and receive static test responses from -your publisher account.

    - -

    Test accounts are standard Google accounts that you register on your -publisher account, such that they will receive the test response for -applications that you have uploaded. Developers can then sign in to their -devices or emulators using the test account credentials and initiate license -checks from installed applications. When the licensing server receives a license -check from a user of a test account, it returns the static test response -configured for the publisher account.

    - -

    Necessarily, there are limitations on the access and permissions given to -users signed in through test accounts, including:

    - - - -

    The table below summarizes the differences in capabilities, between the -publisher account, a test account, and any other account.

    - -

    Table 1. -Differences in account types for testing licensing.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Account TypeCan check license before upload?Can receive test response?Can set test response?
    Publisher accountYesYesYes
    Test accountNoYesNo
    OtherNoNoNo
    - -

    Registering test accounts on the publisher account

    - -

    To get started, you need to register each test account in your publisher -account. As shown in Figure 7, above, you -register test accounts in the Licensing panel of your publisher account's Edit -Profile page. Simply enter the accounts as a comma-delimited list and click -Save to save your profile changes.

    - -

    You can use any Google account as a test account. If you want to own and -control the test accounts, you can create the accounts yourself and distribute -the credentials to your developers or testers.

    - -

    Handling application upload and distribution for test -account users

    - -

    As mentioned above, users of test accounts can only receive static test -responses for applications that are uploaded to the publisher account. Since -those users do not have permission to upload applications, as the publisher you -will need to work with those users to collect apps for upload and distribute -uploaded apps for testing. You can handle collection and distribution in any way -that is convenient.

    - -

    Once an application is uploaded and becomes known to the licensing server, -developers and testers can continue modify the application in their local -development environment, without having to upload new versions. You only need to -upload a new version if the local application increments the -versionCode attribute in the manifest file.

    - -

    Distributing your public key to test account users

    - -

    The licensing server handles static test responses in the normal way, -including signing the license response data, adding extras parameters, and so -on. To support developers who are implementing licensing using test accounts, -rather than the publisher account, you will need to distribute -your public key to them. Developers without access to the publisher site do not -have access to your public key, and without the key they won't be able to -verify license responses.

    - -

    Note that if you decide to generate a new licensing key pair for your account -for some reason, you need to notify all users of test accounts. For -testers, you can embed the new key in the application package and distribute it -to users. For developers, you will need to distribute the new key to them -directly.

    - - -

    Signing in to an authorized account in the runtime -environment

    - -

    The licensing service is designed to determine whether a given user is -licensed to use a given application — during a license check, the Android -Market application gathers the user ID from the primary account on the system -and sends it to the server, together with the package name of the application -and other information. However, if there is no user information available, the -license check cannot succeed, so the Android Market application terminates the -request and returns an error to the application.

    - -

    During testing, to ensure that your application can successfully query the -licensing server, you must make sure that you sign in to an account on the -device or emulator using:

    - - - - - - -

    Signing in using a publisher account offers the advantage of letting your -applications receive static test responses even before the applications are -uploaded to the publisher site.

    - -

    If you are part of a larger organization or are working with external groups -on applications that will be published through your site, you will more likely -want to distribute test accounts instead, then use those to sign in during -testing.

    - -

    To sign in on a device or emulator, follow the steps below. The preferred -approach is to sign in as the primary account — however, if there are -other accounts already in use on the device or emulator, you can create an -additional account and sign in to it using the publisher or test account -credentials.

    - -
      -
    1. Open Settings > Accounts & sync
    2. -
    3. Select Add Account and choose to add a "Google" account. -
    4. -
    5. Select Next and then Sign in.
    6. -
    7. Enter the username and password of either the publisher account or a test -account that is registered in the publisher account.
    8. -
    9. Select Sign in. The system signs you in to the new -account.
    10. -
    - -

    Once you are signed in, you can begin testing licensing in your application -(if you have completed the LVL integration steps above). When your application -initiates a license check, it will receive a response containing the static test -response configured on the publisher account.

    - -

    Note that, if you are using an emulator, you will need to sign in to the -publisher account or test account each time you wipe data when restarting the -emulator.

    - -
    - - -
    Figure 8. Example of -setting up a Google account on a device or emulator.
    -
    - -

    Obfuscating Your Application

    - -

    To ensure the security of your application, particularly for a paid -application that uses licensing and/or custom constraints and protections, it's -very important to obfuscate your application code. Properly obfuscating your -code makes it more difficult for a malicious user to decompile the application's -bytecode, modify it — such as by removing the license check — -and then recompile it.

    - -

    Several obfuscator programs are available for Android applications, including -ProGuard, which also offers -code-optimization features. The use of ProGuard or a similar program to obfuscate -your code is strongly recommended for all applications that use Android -Market Licensing.

    - -

    Publishing a Licensed Application

    - -

    When you are finished testing your license implementation, you are ready to -publish the application on Android Market. Follow the normal steps to prepare, sign, and then publish the application. -

    - -

    Removing Copy Protection

    - -

    After uploading your licensed application, remember to remove copy protection -from the application, if it is currently used. To check and remove copy -protection, sign in to the publisher site and go the application's upload -details page. In the Publishing options section, make sure that the Copy -Protection radio button selection is "Off".

    - -

    Considerations for Free Apps

    - -

    Licensing is currently supported only for paid applications. If you already -published your application as free, you won't be able to upload an updated -version that includes licensing (that is, an application that uses the same -package name and that includes the licensing -permission). Here are some points to keep in mind:

    - - - -

    Where to Get Support

    - -

    If you have questions or encounter problems while implementing or deploying -publishing in your applications, please use the support resources listed in the -table below. By directing your queries to the correct forum, you can get the -support you need more quickly.

    - -

    Table 2. Developer support resources -for Android Market Licensing Service.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Support TypeResourceRange of Topics
    Development and testing issuesGoogle Groups: android-developers -LVL download and integration, library projects, Policy -questions, user experience ideas, handling of responses, Obfuscator, IPC, test -environment setup
    Stack Overflow: http://stackoverflow.com/questions/tagged/android
    Accounts, publishing, and deployment issuesAndroid -Market Help ForumPublisher accounts, licensing key pair, test accounts, server -responses, test responses, application deployment and results
    Market -Licensing Support FAQ
    LVL issue trackerMarketlicensing -project issue trackerBug and issue reports related specifically to the LVL source code classes -and interface implementations
    - -

    For general information about how to post to the groups listed above, see Developer Forums document -in the Resources tab.

    - -

    Summary of LVL Classes and Interfaces

    - -

    The table below lists all of the source files in the License Verification -Library (LVL) available through the Android SDK. All of the files are part of -the com.android.vending.licensing package.

    - -

    Table A-1. Summary of LVL library -classes and interfaces.

    - -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    CategoryNameDescription
    License check and resultLicenseCheckerClass that you instantiate (or subclass) to initiate a license check.
    LicenseCheckerCallbackInterface that you implement to handle result of the license check.
    PolicyPolicyInterface that you implement to determine whether to allow -access to the application, based on the license response.
    ServerManagedPolicyDefault Policy implementation. Uses settings provided by the -licensing server to manage local storage of license data, license validity, -retry.
    StrictPolicyAlternative Policy implementation. Enforces licensing based on a direct -license response from the server only. No caching or request retry.
    Data obfuscation
    (optional)
    ObfuscatorInterface that you implement if you are using a Policy (such as -ServerManagedPolicy) that caches license response data in a persistent store. -Applies an obfuscation algorithm to encode and decode data being written or -read.
    AESObfuscatorDefault Obfuscator implementation that uses AES encryption/decryption -algorithm to obfuscate/unobfuscate data.
    Device limitation
    (optional)
    DeviceLimiterInterface that you implement if you want to restrict use of an -application to a specific device. Called from LicenseValidator. Implementing -DeviceLimiter is not recommended for most applications because it requires a -backend server and may cause the user to lose access to licensed applications, -unless designed with care.
    NullDeviceLimiterDefault DeviceLimiter implementation that is a no-op (allows access to all -devices).
    Library core, no integration neededResponseDataClass that holds the fields of a license response.
    LicenseValidatorClass that decrypts and verifies a response received from the licensing -server.
    ValidationExceptionClass that indicates errors that occur when validating the integrity of data -managed by an Obfuscator.
    PreferenceObfuscatorUtility class that writes/reads obfuscated data to the system's -{@link android.content.SharedPreferences} store.
    ILicensingServiceOne-way IPC interface over which a license check request is passed to the -Android Market client.
    ILicenseResultListenerOne-way IPC callback implementation over which the application receives an -asynchronous response from the licensing server.
    -
    - - -

    Server Response Codes

    - -

    The table below lists all of the license response codes supported by the -licensing server. In general, an application should handle all of these response -codes. By default, the LicenseValidator class in the LVL provides all of the -necessary handling of these response codes for you.

    - -

    Table A-2. Summary of response codes -returned by the Android Market server in a license response.

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Response CodeDescriptionSigned?ExtrasComments
    LICENSEDThe application is licensed to the user. The user has purchased the -application or the application only exists as a draft.YesVTGT, GRAllow access according to Policy constraints.
    LICENSED_OLD_KEYThe application is licensed to the user, but there is an updated application -version available that is signed with a different key. Yes VT, GT, GR, UTOptionally allow access according to Policy constraints. -

    Can indicate that the key pair used by the installed -application version is invalid or compromised. The application can allow access -if needed or inform the user that an upgrade is available and limit further use -until upgrade.

    -
    NOT_LICENSEDThe application is not licensed to the user.NoDo not allow access.
    ERROR_CONTACTING_SERVERLocal error — the Android Market application was not able to reach the -licensing server, possibly because of network availability problems. NoRetry the license check according to Policy retry limits.
    ERROR_SERVER_FAILUREServer error — the server could not load the publisher account's key -pair for licensing.NoRetry the license check according to Policy retry limits. -
    ERROR_INVALID_PACKAGE_NAMELocal error — the application requested a license check for a package -that is not installed on the device. No Do not retry the license check. -

    Typically caused by a development error.

    -
    ERROR_NON_MATCHING_UIDLocal error — the application requested a license check for a package -whose UID (package, user ID pair) does not match that of the requesting -application. No Do not retry the license check. -

    Typically caused by a development error.

    -
    ERROR_NOT_MARKET_MANAGEDServer error — the application (package name) was not recognized by -Android Market. NoDo not retry the license check. -

    Can indicate that the application was not published -through Android Market or that there is an development error in the licensing -implementation.

    -
    - -

    Note: As documented in -Setting Up The Testing Environment, the response code can be manually -overridden for the application developer and any registered test users via the -Android Market publisher site. -

    -Additionally, as noted above, applications that are in draft mode (in other -words, applicaitons that have been uploaded but have never been -published) will return LICENSED for all users, even if not listed as a test -user. Since the application has never been offered for download, it is assumed -that any users running it must have obtained it from an authorized channel for -testing purposes.

    - -

    Server Response Extras

    - -

    The licensing server includes several settings in certain types of license -responses, to assist the application and its Policy in managing access to the -application across the 24-hour refund period and other conditions. Specifically, -the server provides recommended values for the application's license validity -period, retry grace period, maximum allowable retry count, and other settings. -The server appends the settings as key-value pairs in the license response -"extras" field.

    - -

    Any Policy implementation can extract the extras settings from the license -response and use them as needed. The LVL default Policy implementation, ServerManagedPolicy, serves as a working -implementation and an illustration of how to obtain, store, and use the -settings.

    - -

    Table A-3. Summary of -license-management settings supplied by the Android Market server in a license -response.

    - - - - - - - - - - - - - - - - - - - - - - - -
    ExtraDescription
    VTLicense validity timestamp. Specifies the date/time at which the current -(cached) license response expires and must be rechecked on the licensing server. -
    GTGrace period timestamp. Specifies the end of the period during which a -Policy may allow access to the application, even though the response status is -RETRY.

    The value is managed by the server, however a typical value would be 5 -or more days.

    GRMaximum retries count. Specifies how many consecutive RETRY license checks -the Policy should allow, before denying the user access to the application. -

    The value is managed by the server, however a typical value would be "10" or -higher.

    UTUpdate timestamp. Specifies the day/time when the most recent update to -this application was uploaded and published.

    The server returns this extra -only for LICENSED_OLD_KEYS responses, to allow the Policy to determine how much -time has elapsed since an update was published with new licensing keys before -denying the user access to the application.

    - -

    The sections below provide more information about the server-provided -settings and how to use them.

    - -

    License validity period

    - -

    The Android Market licensing server sets a license validity period for all -downloaded applications. The period expresses the interval of time over which an -application's license status should be considered as unchanging and cacheable by -a licensing Policy in the application. The licensing server includes the -validity period in its response to all license checks, appending an -end-of-validity timestamp to the response as an extra under the key "VT". A -Policy can extract the VT key value and use it to conditionally allow access to -the application without rechecking the license, until the validity period -expires.

    - -

    The license validity signals to a licensing Policy when it must recheck the -licensing status with the licensing server. It is not intended to imply -whether an application is actually licensed for use. That is, when an -application's license validity period expires, this does not mean that the -application is no longer licensed for use — rather, it indicates only that -the Policy must recheck the licensing status with the server. It follows that, -as long as the license validity period is not expired, it is acceptable for the -Policy to cache the initial license status locally and return the cached license -status instead of sending a new license check to the server.

    - -

    The licensing server manages the validity period as a means of helping the -application properly enforce licensing across the refund period offered by -Android Market for paid applications. It sets the validity period based on -whether the application was purchased and, if so, how long ago. Specifically, -the server sets a validity period as follows:

    - - - -

    The ServerManagedPolicy implementation uses the extracted timestamp -(mValidityTimestamp) as a primary condition for determining whether -to recheck the license status with the server before allowing the user access to -the application.

    - -

    Retry period and maximum retry count

    - -

    In some cases, system or network conditions can prevent an application's -license check from reaching the licensing server, or prevent the server's -response from reaching the Android Market client application. For example, the -user might launch an application when there is no cell network or data -connection available — such as when on an airplane — or when the -network connection is unstable or the cell signal is weak.

    - -

    When network problems prevent or interrupt a license check, the Android -Market client notifies the application by returning a "RETRY" response code to -the Policy's processServerResponse() method. In the case of system -problems, such as when the application is unable to bind with Android Market's -ILicensingService implementation, the LicenseChecker library itself calls the -Policy processServerResonse() method with a "RETRY" response code. -

    - -

    In general, the RETRY response code is a signal to the application that an -error has occurred that has prevented a license check from completing. - -

    The Android Market server helps an application to manage licensing under -error conditions by setting a retry "grace period" and a recommended maximum -retries count. The server includes these values in all license check responses, -appending them as extras under the keys "GT" and "GR".

    - -

    The application Policy can extract the GT and GR extras and use them to -conditionally allow access to the application, as follows:

    - - - -

    The ServerManagedPolicy uses the server-supplied GT and GR values as -described above. The example below shows the conditional handling of the retry -responses in the allow() method. The count of RETRY responses is -maintained in the processServerResponse() method, not shown.

    - - -
        public boolean allowAccess() {
    -        long ts = System.currentTimeMillis();
    -        if (mLastResponse == LicenseResponse.LICENSED) {
    -            // Check if the LICENSED response occurred within the validity timeout.
    -            if (ts <= mValidityTimestamp) {
    -                // Cached LICENSED response is still valid.
    -                return true;
    -            }
    -        } else if (mLastResponse == LicenseResponse.RETRY &&
    -                   ts < mLastResponseTime + MILLIS_PER_MINUTE) {
    -            // Only allow access if we are within the retry period or we haven't used up our
    -            // max retries.
    -            return (ts <= mRetryUntil || mRetryCount <= mMaxRetries);
    -        }
    -        return false;
    -    }
    - diff --git a/docs/html/guide/publishing/preparing.jd b/docs/html/guide/publishing/preparing.jd index 83aa5eedcdb8..c355479922a2 100644 --- a/docs/html/guide/publishing/preparing.jd +++ b/docs/html/guide/publishing/preparing.jd @@ -291,7 +291,8 @@ current user has purchased it. Using Android Market Licensing is optional even i releasing your app through Android Market.

    For more information about Android Market Licensing Service and how to use it in your -application, see Application Licensing.

    +application, see Application +Licensing.

    Building Your Application for Release

    diff --git a/docs/html/guide/publishing/publishing.jd b/docs/html/guide/publishing/publishing.jd index 49b34d8d2fd6..27a87f944bc1 100644 --- a/docs/html/guide/publishing/publishing.jd +++ b/docs/html/guide/publishing/publishing.jd @@ -74,7 +74,7 @@ Android Market you have access to a suite of developer tools that let you analyz 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.

    +application licensing.

    Before you can publish applications on Android Market, you need to register as an Android Market developer. During the @@ -254,7 +254,7 @@ higher.

    For complete information about Android Market Licensing Service and how to use it in your application, read Application Licensing.

    +href="{@docRoot}guide/market/licensing/index.html">Application Licensing.

    Using Android Market In-app Billing

    diff --git a/docs/html/guide/publishing/publishing_overview.jd b/docs/html/guide/publishing/publishing_overview.jd index 79199c5c674a..c94d20181cb5 100755 --- a/docs/html/guide/publishing/publishing_overview.jd +++ b/docs/html/guide/publishing/publishing_overview.jd @@ -130,7 +130,8 @@ Android Market you have access to a suite of developer tools that let you analyz identify market trends, and control who your applications are being distributed to. You also have access to several revenue-enhancing features that are not available anywhere else, such as in-app billing and application licensing. This rich array of tools +href="{@docRoot}guide/market/licensing/index.html">application licensing. This rich array of +tools and features, coupled with numerous end-user community features, makes Android Market the premier marketplace for selling and buying Android applications.

    diff --git a/docs/html/guide/topics/manifest/manifest-element.jd b/docs/html/guide/topics/manifest/manifest-element.jd index d737a67a9058..c970c7244140 100644 --- a/docs/html/guide/topics/manifest/manifest-element.jd +++ b/docs/html/guide/topics/manifest/manifest-element.jd @@ -152,7 +152,7 @@ either internal or external storage through the system settings.

    Caution: If your application uses the Android Market's Copy Protection feature, it cannot be installed to a device's SD card. However, if you use Android - Market's Application Licensing instead, + Market's Application Licensing instead, your application can be installed to internal or external storage, including SD cards.

    Note: By default, your application will be installed on the diff --git a/docs/html/sitemap.txt b/docs/html/sitemap.txt index 0298a8ed28c1..182e958fc450 100644 --- a/docs/html/sitemap.txt +++ b/docs/html/sitemap.txt @@ -108,7 +108,7 @@ http://developer.android.com/guide/topics/testing/activity_testing.html http://developer.android.com/guide/topics/testing/contentprovider_testing.html http://developer.android.com/guide/topics/testing/service_testing.html http://developer.android.com/guide/topics/testing/what_to_test.html -http://developer.android.com/guide/publishing/licensing.html +http://developer.android.com/guide/market/licensing/index.html http://developer.android.com/guide/market/billing/index.html http://developer.android.com/guide/market/billing/billing_about.html http://developer.android.com/guide/market/billing/billing_overview.html -- cgit v1.2.3-59-g8ed1b