Home | History | Annotate | Download | only in publishing
      1 page.title=Licensing Your Applications
      2 @jd:body
      3 
      4 <div id="qv-wrapper">
      5 <div id="qv">
      6 
      7   <h2>Quickview</h2>
      8   <ul>
      9     <li>Licensing lets you protect your application on any device that includes Android Market.</li>
     10     <li>Your app maintains control of how it enforces its licensing status. </li>
     11     <li>Adding licensing to an app is straightforward, using the library available through the SDK.</li>
     12     <li>The service is free and is available to all developers who publish on Android Market. </li>
     13   </ul>
     14 
     15   <h2>In this document</h2>
     16   <ol>
     17     <li><a href="#account">Setting Up A Publisher Account</a></li>
     18     <li><a href="#dev-setup">Setting Up the Development Environment</a></li>
     19     <li><a href="#app-integration">Integrating the LVL with Your Application</a>
     20     <ol>
     21        <li><a href="#add-library">Including the LVL</a></li>
     22        <li><a href="#manifest-permission">Adding the licensing permission</a></li>
     23        <li><a href="#impl-Policy">Implementing a Policy</a></li>
     24        <li><a href="#impl-Obfuscator">Implementing an Obfuscator</a></li>
     25        <li><a href="#impl-lc">Checking the license</a></li>
     26        <li><a href="#impl-DeviceLimiter">Implementing a DeviceLimiter</a></li>
     27     </ol></li>
     28     <li><a href="#test-env">Setting Up the Test Environment</a>
     29     <ol>
     30        <li><a href="#test-response">Test responses</a></li>
     31        <li><a href="#test-acct-setup">Test accounts</a></li>
     32        <li><a href="#acct-signin">Signing in on a device or emulator</a></li>
     33     </ol></li>
     34     <li><a href="#app-obfuscation">Obfuscating Your Application</a></li>
     35     <li><a href="#app-publishing">Publishing a Licensed Application</a></li>
     36     <li><a href="#support">Where to Get Support</a></li>
     37   </ol>
     38 
     39   <h2>Appendix</h2>
     40   <ol>
     41     <li><a href="#lvl-summary">Summary of LVL Classes and Interfaces</a></li>
     42     <li><a href="#server-response-codes">Server Response Codes</a></li>
     43     <li><a href="#extras">Server Response Extras</a></li>
     44   </ol>
     45 
     46 </div>
     47 </div>
     48 
     49 <p>Android Market offers a licensing service that lets you enforce licensing
     50 policies for paid applications that you publish through Android Market. With
     51 Android Market Licensing, your applications can query Android Market at run time to
     52 obtain their licensing status for the current user, then allow or disallow
     53 further use as appropriate. </p>
     54 
     55 <p>Using the service, you can apply a flexible licensing policy on an
     56 application-by-application basis &mdash; each application can enforce licensing
     57 in the way most appropriate for it. If necessary, an application can apply custom
     58 constraints based on the licensing status obtained from Android Market.
     59 For example, an application can check the licensing status and then apply custom
     60 constraints that allow the user to run it unlicensed for a specific number
     61 of times, or for a specific validity period. An application can also restrict use of the
     62 application to a specific device, in addition to any other constraints. </p>
     63 
     64 <p>The licensing service is a secure means of controlling access to your
     65 applications. When an application checks the licensing status, the Market server
     66 signs the licensing status response using a key pair that is uniquely associated
     67 with the publisher account. Your application stores the public key in its
     68 compiled <code>.apk</code> file and uses it to verify the licensing status
     69 response.</p>
     70 
     71 <p>Any application that you publish through Android Market can use the Android
     72 Market Licensing service. No special account or registration is needed.
     73 Additionally, because the service uses no dedicated framework APIs, you can add
     74 licensing to any legacy application that uses a minimum API level of 3 or
     75 higher.</p>
     76 
     77 <p>To help you add licensing to your application, the Android SDK provides
     78 library sources that you can include in your application project. The
     79 License Verification Library (LVL) handles all of
     80 the licensing-related communication with the Android Market client and the
     81 licensing service. With the LVL integrated, your application can determine its
     82 licensing status for the current user by simply calling a library checker method
     83 and implementing a callback that receives the status.</p>
     84 
     85 <p>This document explains how the licensing service works and how to add it to
     86 your application. </p>
     87 
     88 
     89 <h2 id="overview">Overview</h2>
     90 
     91 <p>Android Market Licensing is a network-based service that lets an application
     92 on an Android-powered device query a trusted licensing server, to determine
     93 whether the application is licensed to the current device user. After receiving
     94 the server response, the application can then allow or disallow further use of
     95 the application as needed. In the service, the role of the licensing server is
     96 to provide the license status for the current user; the application itself is
     97 responsible for querying the server and conditionally granting access to the
     98 application. </p>
     99 
    100 <h4>Application, Android Market client, and server</h4>
    101 
    102 <p>The licensing service is based on the capability of the Android Market server
    103 to determine whether a given user is licensed to use a given application. The
    104 server considers a user licensed if the user is recorded to have purchased the
    105 application, or if the application is available for free. To properly identify
    106 the user and determine the license status, the server requires information about
    107 the application and user &mdash; the application and the Android Market client
    108 work together to assemble the information and pass it to the server. </p>
    109 
    110 <p>In the licensing service, an application does not query the licensing server
    111 directly, but instead calls the Android Market client over remote IPC to
    112 initiate a license request. In the license request:</p>
    113 
    114 <ul>
    115 <li>The application provides its package name and a nonce that is later used to
    116 validate any response from the server, as well as a callback over which the
    117 response can be returned asynchronously.</li>
    118 <li>The Android Market client, which has greater permissions than the
    119 application, collects the necessary information about the user and the device,
    120 such as the device's primary Google account username, IMSI, and other
    121 information. It then sends the license check request to the server on behalf of
    122 the application.</li>
    123 <li>The server evaluates the request using all available information, attempting
    124 to establish the user's identity to a sufficient level of confidence. The server
    125 then checks the user identity against purchase records for the application and
    126 returns a license response, which the Android Market client returns to the
    127 application over the IPC callback.</li>
    128 </ul>
    129 
    130 <p>Notice that during a license check, the application does not manage any
    131 network connections or use any licensing related APIs in the Android platform.
    132 </p>
    133 
    134 <div class="figure" style="width:469px">
    135 <img src="{@docRoot}images/licensing_arch.png" alt=""/>
    136 <p class="img-caption"><strong>Figure 1.</strong> Your application initiates a
    137 license check through the LVL and the Android Market
    138 client, which handles communication with the Market server.</p>
    139 </div>
    140 
    141 <h4>License responses secured through public key cryptography</h4>
    142 
    143 <p>To ensure the integrity of each license query, the server signs the license
    144 response data using an RSA key pair that is shared exclusively between the
    145 server and the application publisher.</p>
    146 
    147 <p>The licensing service generates a single licensing key pair for each
    148 publisher account and exposes the public key in the account's profile page. The
    149 publisher copies the public key and embeds it in the application source code,
    150 then compiles and publishes the <code>.apk.</code> The server retains the
    151 private key internally and uses it to sign license responses for applications
    152 published on that account. </p>
    153 
    154 <p>When the application receives a signed response, it uses the embedded public
    155 key to verify the data. The use of public key cryptography in the licensing
    156 service makes it possible for the application to detect responses that have been
    157 tampered with or that are spoofed.</p>
    158 
    159 <h4>Use of licensing in your application</h4>
    160 
    161 <p>To use licensing in your application, add code to the application to
    162 initiate a license check request and handle the response when it is received.
    163 You can choose when, and how often, you want your application to check its
    164 license and you have full control over how it handles the response, verifies the
    165 signed response data, and enforces access controls. </p>
    166 
    167 <p>To simplify the process of adding support for licensing, download and
    168 integrate the Licensing Verification Library, described below. Integration is
    169 straightforward.</p>
    170 
    171 <p>When you are finished integrating the LVL, use a test environment
    172 provided by the publisher site to test your application's handling of server
    173 responses. </p>
    174 
    175 <p>Finally, publish the application <code>.apk</code> on Market using the
    176 normal process. If you previously used the copy-protection provided by Android
    177 Market, you can remove it from applications that use licensing. </p>
    178 
    179 <h4>Licensing Verification Library simplifies implementation</h4>
    180 
    181 <p>The Android SDK includes a License Verification Library (LVL) that you can
    182 download and use as the basis for your application's licensing implementation.
    183 The LVL greatly simplifies the process of adding licensing to your application
    184 and helps ensure a more secure, robust implementation for your application. The
    185 LVL provides internal classes that handle most of the standard operations of a
    186 license query, such as contacting Android Market to initiate a license request
    187 and verifying and validating the responses. It also exposes key interfaces that
    188 let you easily plug in your custom code for defining licensing policy and
    189 managing access as needed by your application. The key LVL interfaces are: </p>
    190 
    191 <ul>
    192 <li>Policy &mdash; your implementation determines whether to allow access to the
    193 application, based on the license response received from the server and any
    194 other data available (such as from a backend server associated with your
    195 application). The implementation can evaluate the various fields of the license
    196 response and apply other constraints, if needed. The implementation also lets
    197 you manage the handling of license checks that result in errors, such as network
    198 errors.</li>
    199 <li>LicenseCheckerCallback &mdash; your implementation manages access to the
    200 application, based on the result of the Policy's handling of the license
    201 response. Your implementation can manage access in any way needed, including
    202 displaying the license result in the UI or directing the user to purchase the
    203 application (if not currently licensed). </li>
    204 </ul>
    205 
    206 <p>To help you get started with a Policy, the LVL provides two fully complete
    207 Policy implementations that you can use without modification or adapt to your
    208 needs:</p>
    209 
    210 <ul>
    211 <li><a href="#ServerManagedPolicy">ServerManagedPolicy</a> is a flexible Policy
    212 that uses settings provided by the licensing server to manage response caching
    213 and access to the application while the device is offline (such as when the
    214 user is on an airplane). For most applications, the use of
    215 ServerManagedPolicy is highly recommended. </li>
    216 <li><a href="#StrictPolicy">StrictPolicy</a> is a restrictive Policy that
    217 does not cache any response data and allows the application access <em>only</em>
    218 when the server returns a licensed response.</li>
    219 </ul>
    220 
    221 <p>The LVL is available as a downloadable component of the Android SDK. The
    222 component includes both the LVL itself and an example application that shows how
    223 the library should be integrated with your application and how your application
    224 should manage response data, UI interaction, and error conditions. </p>
    225 
    226 <p>The LVL sources are provided as an Android <em>library project</em>, which
    227 means that you can maintain a single set of library sources and share them
    228 across multiple applications. A full test environment is also available through
    229 the SDK, so you can develop and test the licensing implementation in your
    230 applications before publishing them, even if you don't have access to a
    231 physical device.</p>
    232 
    233 <h4>Requirements and limitations</h4>
    234 
    235 <p>Android Market Licensing is designed to let you apply license controls to
    236 applications that you publish through Android Market. The service is not
    237 designed to let you control access to applications that are not published
    238 through Android Market or that are run on devices that do not offer the Android
    239 Market client. </p>
    240 
    241 <p>Here are some points to keep in mind as you implement licensing in your
    242 application: </p>
    243 
    244 <ul>
    245 <li>Only paid applications published through Market can use the
    246 service. </li>
    247 <li>An application can use the service only if the Android Market client is
    248 installed on its host device and the device is running Android 1.5 (API level 3)
    249 or higher.</li>
    250 <li>To complete a license check, the licensing server must be accessible over
    251 the network. You can implement license caching behaviors to manage access when
    252 there is no network connectivity. </li>
    253 <li>The security of your application's licensing controls ultimately relies on
    254 the design of your implementation itself. The service provides the building
    255 blocks that let you securely check licensing, but the actual enforcement and
    256 handling of the license are factors in your control. By following the best
    257 practices in this document, you can help ensure that your implementation will be
    258 secure.</li>
    259 <li>Adding licensing to an application does not affect the way the application
    260 functions when run on a device that does not offer Android Market.</li>
    261 <li>Licensing is currently for paid apps only, since free apps are considered
    262 licensed for all users. If your application is already published as free, 
    263 you won't be able to upload a new version that uses licensing.</li>
    264 </ul>
    265 
    266 <h4>Replacement for copy protection</h4>
    267 
    268 <p>Android Market Licensing is a flexible, secure mechanism for controlling
    269 access to your applications. It effectively replaces the copy-protection
    270 mechanism offered on Android Market and gives you wider distribution
    271 potential for your applications. </p>
    272 
    273 <ul>
    274 <li>A limitation of the legacy copy-protection mechanism on Android Market is
    275 that applications using it can be installed only on compatible devices that
    276 provide a secure internal storage environment. For example, a copy-protected
    277 application cannot be downloaded from Market to a device that provides root
    278 access, and the application cannot be installed to a device's SD card. </li>
    279 <li>With Android Market licensing, you can move to a license-based model in
    280 which access is not bound to the characteristics of the host device, but to your
    281 publisher account on Android Market and the licensing policy that you define.
    282 Your application can be installed and controlled on any compatible device on
    283 any storage, including SD card.</li>
    284 </ul>
    285 
    286 <p>Although no license mechanism can completely prevent all unauthorized use,
    287 the licensing service lets you control access for most types of normal usage,
    288 across all compatible devices, locked or unlocked, that run Android 1.5 or
    289 higher version of the platform.</p>
    290 
    291 <p>The sections below describe how to add Android Market licensing to your
    292 applications. </p>
    293 
    294 <h2 id="account">Setting Up a Publisher Account</h2>
    295 
    296 <p>Android Market licensing lets you manage access to applications that
    297 users have downloaded from Android Market. To use licensing in an application,
    298 you need to have a publisher account on Android Market so that you can
    299 publish the application to users. </p>
    300 
    301 <p>If you don't already have a publisher account, you need to register for one
    302 using your Google account and agree to the terms of service. Once you are
    303 registered, you can upload applications at your convenience and begin debugging
    304 and testing your licensing implementation. For more information about publishing
    305 on Android Market, see <a
    306 href="{@docRoot}guide/publishing/publishing.html">Publishing Your
    307 Applications</a></p>
    308 
    309 <p>To register as an Android Market developer and set up your publisher account,
    310 visit the Android Market publisher site:</p>
    311 
    312 <p style="margin-left:2em;"><a
    313 href="http://market.android.com/publish">http://market.android.com/publish</a>
    314 </p>
    315 
    316 <p>If you already have a publisher account on Android Market, use your existing
    317 account to set up licensing. You <em>do not</em> need to register for a new
    318 account to support licensing (and doing so is not recommended, especially if you
    319 are adding licensing support to applications that you have already published).
    320 In all cases, if you have published applications, you manage licensing for those
    321 applications through the account on which the applications are published. </p>
    322 
    323 <p>Once your publisher account is set up, use the account to:</p>
    324 
    325 <ul>
    326 <li>Obtain a public key for licensing</li>
    327 <li>Debug and test an application's licensing implementation, prior to
    328 publishing the application</li>
    329 <li>Publish the applications to which you have added licensing support</li>
    330 </ul>
    331 
    332 <h4>Administrative settings for licensing</h4>
    333 
    334 <p>Once you are signed into your publisher account, you can manage several
    335 administrative controls for Android Market licensing. The controls are available
    336 in the Edit Profile page, in the "Licensing" panel, shown below. The controls
    337 let you: </p>
    338 
    339 <ul>
    340 <li>Set up multiple "test accounts", identified by email address. The licensing
    341 server allows users signed into test accounts on a device or emulator to send
    342 license checks and receive static test responses.</li>
    343 <li>Obtain the account's public key for licensing. When you are implementing
    344 licensing in an application, you must copy the public key string into the
    345 application.</li>
    346 <li>Configure static test responses that the server sends, when it receives a
    347 license check for an application uploaded to the publisher account, from a user
    348 signed in to the publisher account or a test account.</li>
    349 </ul>
    350 
    351 <div style="margin-bottom:2em;">
    352 
    353 <img src="{@docRoot}images/licensing_public_key.png" style="text-align:left;margin-bottom:0;" />
    354 <div style="margin:0 2em;padding:0"><strong>Figure 2.</strong> The Licensing
    355 panel of your account's Edit Profile page lets you manage administrative
    356 settings for licensing.</div>
    357 </div>
    358 
    359 <p>For more information about how to work with test accounts and static test
    360 responses, see <a href="#test-env">Setting Up a Testing Environment</a>, below.
    361 
    362 <h2 id="dev-setup">Setting Up the Development Environment</h2>
    363 
    364 <p>Once you've set up your publisher account on Android Market, the next step is
    365 to set up your development environment for licensing. </p>
    366 
    367 <p>Setting up your environment for licensing involves these tasks:</p>
    368 
    369 <ol>
    370 <li><a href="#download-sdk">Downloading the latest SDK</a>, if you haven't already done so </li>
    371 <li><a href="#runtime-setup">Setting up the runtime environment</a> for development</a></li>
    372 <li><a href="#download-lvl">Downloading the Market Licensing component</a> into your SDK </li>
    373 <li><a href="#lvl-setup">Setting up the Licensing Verification Library</a></li>
    374 <li><a href="#add-library">Including the LVL library project in your application</a></li>
    375 </ol>
    376 
    377 <p>The sections below describe these tasks. When you are done with setup,
    378 you can begin <a href="#app-integration">integrating the LVL into your applications</a>.</p>
    379 
    380 <p>To get started, you need to set up a proper runtime environment on which
    381 you can run, debug and test your application's implementation of license
    382 checking and enforcement. </p>
    383 
    384 
    385 <h3 id="download-sdk">Downloading the latest SDK</h3>
    386 
    387 <div class="sidebox-wrapper">
    388 <div class="sidebox">
    389 <h2>Licensing sample application</h2>
    390 
    391 <p>To work with Android Market licensing, you need a functioning Android
    392 application to which you can add licensing support. </p>
    393 
    394 <p style="margin-top:.5em;">If you are new to Android
    395 and don't yet have a functioning application, the LVL component includes a sample
    396 application that you can set up as a new application project. The sample provides
    397 a complete, working example of how licensing works. For more information, see <a
    398 href="#download-lvl">Downloading the LVL</a>.</p>
    399 
    400 </div>
    401 </div>
    402 
    403 <p>If you haven't done so, you need to download the Android SDK before you can
    404 develop Android applications. The SDK provides the tools that you need to build
    405 and debug Android applications, including applications that use Android Market
    406 licensing. For complete information, including installation instructions, see
    407 the <a href="{@docRoot}sdk/index.html">Android SDK</a>. </p>
    408 
    409 <p>If you have already installed the SDK, make sure to update the
    410 SDK tools and ADT Plugin to the latest versions. You can update the SDK tools
    411 using the Android SDK and AVD Manager and ADT through <strong>Help</strong> &gt;
    412 <strong>Software Updates...</strong> in Eclipse. </p>
    413 
    414 <p>After you've installed the latest SDK and tools, set up your development
    415 environment as described below. </p>
    416 
    417 
    418 <h3 id="runtime-setup">Setting up the runtime environment</h3>
    419 
    420 <p>As described earlier, applications check licensing status not by contacting
    421 the licensing server directly, but by binding to a service provided by the
    422 Android Market application and initiating a license check request. The Android
    423 Market service then handles the direct communication with the licensing server
    424 and finally routes the response back to your application. To debug and test
    425 licensing in your application, you need to set up a runtime environment that
    426 includes the necessary Android Market service, so that your application is able
    427 to send license check requests to the licensing server. </p>
    428 
    429 <p>There are two types of runtime environment that you can use: </p>
    430 
    431 <ul>
    432 <li>An Android-powered device that includes the Android Market application, or</li>
    433 <li>An Android emulator running the Google APIs Add-on, API level 8 (release 2)
    434 or higher</li>
    435 </ul>
    436 
    437 <p>The sections below provide more information. </p>
    438 
    439 <h4 id="runtime-device">Running on a device</h4>
    440 
    441 <p>You can use an Android-powered device as the runtime environment for
    442 debugging and testing licensing on your application.</p>
    443 
    444 <p>The device you use must:</p>
    445 
    446 <ul>
    447 <li>Run a standard version of the Android 1.5 or later (API level
    448 3 or higher) platform, <em>and</em> </li>
    449 <li>Run a system image on which the Android Market client application
    450 is preinstalled. </li>
    451 </ul>
    452 
    453 <p>If Android Market is not preinstalled in the system image, your application won't
    454 be able to communicate with the Android Market licensing server. </p>
    455 
    456 <p>For general information about how to set up a device for use in developing
    457 Android applications, see <a
    458 href="{@docRoot}guide/developing/device.html">Developing on a Device</a>.</p>
    459 
    460 <h4 id="runtime-emulator">Running on an Android emulator</h4>
    461 
    462 <p>You can also use an Android emulator as your runtime
    463 environment for debugging and testing licensing.</p>
    464 
    465 <p>Because the standard Android platforms provided in the Android SDK <em>do
    466 not</em> include Android Market, you need to download the Google APIs Add-On
    467 platform, API Level 8 (or higher), from the SDK repository. After downloading
    468 the add-on, you need to create an AVD configuration that uses that system image.
    469 </p>
    470 
    471 <p>The Google APIs Add-On does not include the full Android Market client.
    472 However, it does provide: </p>
    473 
    474 <ul>
    475 <li>An Android Market background service that implements the
    476 ILicensingService remote interface, so that your application can
    477 send license checks over the network to the licensing server. </li>
    478 <li>A set of underlying account services that let you add an a Google account on
    479 the AVD and sign in using your publisher account or test account credentials.
    480 Signing in using your publisher or test account enables you to debug and test
    481 your application without having publish it. For more information see <a
    482 href="#acct-signin">Signing in to an authorized account</a>, below.</li>
    483 </ul>
    484 
    485 <p>Several versions of the add-on are available in the SDK repository, but only
    486 <strong>Google APIs Add-On, API 8 (release 2) or higher</strong> version of the
    487 add-on includes the necessary Android Market services. This means that you
    488 cannot use Google APIs Add-On API 7 or lower as a runtime environment for
    489 developing licensing on an emulator.</p>
    490 
    491 <div style="margin-bottom:2em;">
    492 
    493 <img src="{@docRoot}images/licensing_gapis_8.png" style="text-align:left;margin-bottom:0;" />
    494 <div style="margin:0 2em;padding:0"><strong>Figure 3.</strong> Google APIs
    495 Add-On, API 8 (release 2) or higher lets you debug and test your licensing
    496 implementation in an emulator.</div>
    497 </div>
    498 
    499 <p>To set up an emulator for adding licensing to an application, follow
    500 these steps: </p>
    501 
    502 <ol>
    503   <li>Launch the Android SDK and AVD Manager. </li>
    504   <li>In the <strong>Available Packages</strong> panel, select and download the
    505 SDK component "Google APIs (Google Inc.) - API Level 8" (or higher) from the SDK
    506 repository, as shown in the figure above.
    507   <p>When the download is complete, use the Android SDK and AVD Manager to
    508 create a new AVD based on that component, described next.</p></li>
    509   <li>In the <strong>Virtual
    510 Devices</strong> panel of the Android SDK and AVD Manager, click
    511 <strong>New</strong> and set the configuration details for the new AVD. </li>
    512   <li>In the dialog that appears, assign a descriptive name to the AVD and then
    513 use the "Target" menu to choose the "Google APIs (Google Inc.) - API Level 8" as
    514 the system image to run on the new AVD. Set the other configuration details as
    515 needed and then click <strong>Create AVD</strong> to finish. The SDK tools
    516 create the new AVD configuration, which then appears in the list of available
    517 Android Virtual Devices.</li>
    518 </ol>
    519 
    520 <p>If you are not familiar with AVDs or how to use them, see <a
    521 href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>.</p>
    522 
    523 <h4 id="project-update">Updating your project configuration</h4>
    524 
    525 <p>After you set up a runtime environment that meets the requirements described
    526 above &mdash; either on an actual device or on an emulator &mdash; make sure to
    527 update your application project or build scripts as needed, so that your compiled
    528 <code>.apk</code> files that use licensing are deployed into that environment.
    529 In particular, if you are developing in Eclipse, make sure that you set up a
    530 Run/Debug Configuration that targets the appropriate device or AVD. </p>
    531 
    532 <p>You do not need to make any changes to your application's
    533 build configuration, provided that the project is already configured to compile
    534 against a standard Android 1.5 (API level 3) or higher library. For example:
    535 
    536 <ul>
    537 <li>If you have an existing application that is compiled against
    538 the Android 1.5 library, you do not need to make any changes to your
    539 build configuration to support licensing. The build target meets the minimum
    540 requirements for licensing, so you would continue building
    541 against the same version of the Android platform.</li>
    542 
    543 <li>Similarly, if you are building against Android 1.5 (API level 3) but
    544 are using an emulator running the Google APIs Add-On API 8 as the application's
    545 runtime environment, there is no need to change your application's build
    546 configuration. </li>
    547 </ul>
    548 
    549 <p>In general, adding licensing to an application should have no impact
    550 whatsoever on the application's build configuration.</p>
    551 
    552 
    553 <h3 id="download-lvl">Downloading the LVL</h3>
    554 
    555 <p>The License Verification Library (LVL) is a collection of helper classes that
    556 greatly simplify the work that you need to do to add licensing to your
    557 application. In all cases, we recommend that you download the LVL and use it as
    558 the basis for the licensing implementation in your application.</p>
    559 
    560 <p>The LVL is available as a downloadable component of the Android SDK. The
    561 component includes: </p>
    562 
    563 <ul>
    564 <li>The LVL sources, stored inside an Android library project. </li>
    565 <li>An example application called "sample" that depends on the LVL library
    566 project. The example illustrates how an application uses the library helper
    567 classes to check and enforce licensing.</li>
    568 </ul>
    569 
    570 <p>To download the LVL component into your development environment, use the
    571 Android SDK and AVD Manager. Launch the Android SDK and AVD Manager and then
    572 select the "Market Licensing" component, as shown in the figure below.
    573 Accept the terms and click <strong>Install Selected</strong> to begin the download. </p>
    574 
    575 <div style="margin-bottom:2em;">
    576 
    577 <img src="{@docRoot}images/licensing_package.png" style="text-align:left;margin-bottom:0;" />
    578 <div style="margin:0 2em;padding:0"><strong>Figure 4.</strong> The Market
    579 Licensing package contains the LVL and the LVL sample application. </div>
    580 </div>
    581 
    582 <p>When the download is complete, the Android SDK and AVD Manager installs both
    583 the LVL library project and the example application into these directories: </p>
    584 
    585 <p style="margin-left:2em"><code>&lt;<em>sdk</em>&gt;/market_licensing/library/</code>
    586 &nbsp;&nbsp;(the LVL library project)<br />
    587 <code>&lt;<em>sdk</em>&gt;/market_licensing/sample/</code>&nbsp;&nbsp;(the example
    588 application)</p>
    589 
    590 <p>If you aren't familiar with how to download components into your SDK, see the
    591 <a href="{@docRoot}sdk/adding-components.html">Adding SDK Components</a>
    592 document. </p>
    593 
    594 
    595 <h3 id="lvl-setup">Setting Up the Licensing Verification Library</h3>
    596 
    597 <p>After downloading the LVL to your computer, you need to set it up in your
    598 development environment, either as an Android library project or by
    599 copying (or importing) the library sources directly into your existing
    600 application package. In general, using the LVL as a library project is recommended,
    601 since it lets you reuse your licensing code across multiple applications and
    602 maintain it more easily over time. Note that the LVL is not designed to be
    603 compiled separately and added to an application as a static .jar file. </p>
    604 
    605 <h4>Moving the library sources to a new location</h4>
    606 
    607 <p>Because you will be customizing the LVL sources to some extent, you should
    608 make sure to <em>move or copy</em> the library sources (the entire
    609 directory at <code>&lt;<em>sdk</em>&gt;/market_licensing/library/</code>)
    610 to a working directory outside of the SDK. You should then use the relocated
    611 sources as your working set. If you are using a source-code management
    612 system, add and track the sources that are in the working location rather
    613 than those in default location in the SDK. </p>
    614 
    615 <p>Moving the library sources is important is because, when you later update the
    616 Market licensing package, the SDK installs the new files to the same location as
    617 the older files. Moving your working library files to a safe location ensures
    618 that your work won't be inadvertently overwritten should you download a new
    619 version of the LVL.</p>
    620 
    621 <h4>Creating the LVL as a library project</h4>
    622 
    623 <div class="sidebox-wrapper">
    624 <div class="sidebox">
    625 <h2>Working with library projects</h2>
    626 
    627 <p>The LVL is provided as an Android library project, which means that you can
    628 share its code and resources across multiple applications. </p>
    629 
    630 <p style="margin-top:.5em;">If you aren't familiar with library projects or how
    631 to use them, read more in <a
    632 href="{@docRoot}guide/developing/eclipse-adt.html#libraryProject">Developing in
    633 Eclipse with ADT</a> or <a
    634 href="{@docRoot}guide/developing/other-ide.html#libraryProject">Developing in
    635 Other IDEs</a>, as appropriate for your environment.</p>
    636 
    637 </div>
    638 </div>
    639 
    640 <p>The recommended way of using the LVL is setting it up as a new Android
    641 <em>library project</em>. A library project is a type of development project
    642 that holds shared Android source code and resources. Other Android application
    643 projects can reference the library project and, at build time, include its
    644 compiled sources in their <code>.apk</code> files. In the context of licensing,
    645 this means that you can do most of your licensing development once, in a library
    646 project, then include the library sources in your various application projects.
    647 In this way, you can easily maintain a uniform implementation of licensing
    648 across all of your projects and maintain it centrally. </p>
    649 
    650 <p>The LVL is provided as a configured library project &mdash; once you have
    651 downloaded it, you can start using it right away. </p>
    652 
    653 <p>If you are working in Eclipse with ADT, you need to add the LVL to your
    654 workspace as a new development project, in the same way as you would a new
    655 application project. </p>
    656 
    657 <ol>
    658 <li>Use the New Project Wizard to create a new
    659 project from existing sources. Select the LVL's <code>library</code> directory
    660 (the directory containing the library's AndroidManifest.xml file) as the project
    661 root.</li>
    662 <li>When you are creating the library project, you can select any application
    663 name, package, and set other fields as needed. </li>
    664 <li>For the library's build target, select Android 1.5 (API level 3) or higher.</li>
    665 </ol>
    666 
    667 <p> When created, the project is
    668 predefined as a library project in its <code>default.properties</code> file, so
    669 no further configuration is needed. </p>
    670 
    671 <p>For more information about how to create an application project or work with
    672 library projects in Eclipse, see <a
    673 href="{@docRoot}guide/developing/eclipse-adt.html#CreatingAProject">Developing
    674 in Eclipse with ADT</a>.</p>
    675 
    676 <h4>Copying the LVL sources to your application</h4>
    677 
    678 <p>As an alternative to adding the LVL as a library project, you can copy the
    679 library sources directly into your application. To do so, copy (or import) the
    680 LVL's <code>library/src/com</code> directory into your application's
    681 <code>src/</code> directory.</p>
    682 
    683 <p>If you add the LVL sources directly to your application, you can skip the
    684 next section and start working with the library, as described in <a
    685 href="#app-integration"></a>.</p>
    686 
    687 
    688 <h3 id="add-library">Including the LVL library project sources in your
    689 application</h3>
    690 
    691 <p>If you want to use the LVL sources as a library project, you need to add a
    692 reference to the LVL library project in your application project properties. This tells
    693 build tools to include the LVL library project sources in your application at
    694 compile time. The process for adding a reference to a library project depends
    695 on your development environment, as described below.</p>
    696 
    697 <p> If you are developing in Eclipse with ADT, you should already have added the
    698 library project to your workspace, as described in the previous section. If you
    699 haven't done that already, do it now before continuing. </p>
    700 
    701 <p>Next, open the application's project properties window, as shown below.
    702 Select the "Android" properties group and click <strong>Add</strong>, then
    703 choose the LVL library project (com_android_vending_licensing) and click
    704 <strong>OK</strong>. For more information, see
    705 <a href="{@docRoot}guide/developing/eclipse-adt.html#libraryProject">Developing
    706 in Eclipse with ADT</a></p>
    707 
    708 <div style="margin-bottom:2em;">
    709 
    710 <img src="{@docRoot}images/licensing_add_library.png" style="text-align:left;margin-bottom:0;" />
    711 <div style="margin:0 2em;padding:0"><strong>Figure 5.</strong> If you are
    712 working in Eclipse with ADT, you can add the LVL library project to your
    713 application from the application's project properties.</div>
    714 </div>
    715 
    716 <p>If you are developing using the SDK command-line tools, navigate to the
    717 directory containing your application project and open the
    718 <code>default.properties</code> file. Add a line to the file that specifies the
    719 <code>android.library.reference.&lt;n&gt;</code> key and the path to the
    720 library. For example: </p>
    721 
    722 <pre>android.library.reference.1=path/to/library_project</pre>
    723 
    724 <p>Alternatively, you can use this command to update the project
    725 properties, including the reference to the library project:</p>
    726 
    727 <pre class="no-pretty-print" style="color:black">android update lib-project
    728 --target <em>&lt;target_ID&gt;</em> \
    729 --path <em>path/to/my/app_project</em> \
    730 --library <em>path/to/my/library_project</em>
    731 </pre>
    732 
    733 <p>For more information about working with library projects, see <a
    734 href="{@docRoot}guide/developing/eclipse-adt.html#libraryProject">Developing
    735 in Eclipse with ADT</a> or <a
    736 href="{@docRoot}guide/developing/other-ide.html#libraryProject">Developing in
    737 Other IDEs</a>, as appropriate for your environment.</p>
    738 
    739 
    740 <h2 id="app-integration">Integrating the LVL with Your Application</h2>
    741 
    742 <p>Once you've followed the steps above to set up a publisher account and
    743 development environment, you are ready to begin integrating the LVL with your
    744 application. </p>
    745 
    746 <p>Integrating the LVL with your application code involves these tasks:</p>
    747 
    748 <ol>
    749 <li><a href="#manifest-permission">Adding the licensing permission</a> your application's manifest.</li>
    750 <li><a href="#impl-Policy">Implementing a Policy</a> &mdash; you can choose one of the full implementations provided in the LVL or create your own.</li>
    751 <li><a href="#impl-Obfuscator">Implementing an Obfuscator</a>, if your Policy will cache any license response data. </li>
    752 <li><a href="#impl-lc">Adding code to check the license</a> in your application's main Activity</li>
    753 <li><a href="#impl-DeviceLimiter">Implementing a DeviceLimiter</a> (optional and not recommended for most applications)</li>
    754 </ol>
    755 
    756 <p>The sections below describe these tasks. When you are done with the
    757 integration, you should be able to compile your application successfully and you
    758 can begin testing, as described in <a href="#test-env">Setting Up the Test
    759 Environment</a>.</p>
    760 
    761 <p>For an overview of the full set of source files included in the LVL, see <a
    762 href="#lvl-summary">Summary of LVL Classes and Interfaces</a>.</p>
    763 
    764 
    765 <h3 id="manifest-permission">Adding the licensing permission to your
    766 AndroidManifest.xml</h3>
    767 
    768 <p>To use the Android Market application for sending a license check to the
    769 server, your application must request the proper permission,
    770 <code>com.android.vending.CHECK_LICENSE</code>. If your application does
    771 not declare the licensing permission but attempts to initiate a license check,
    772 the LVL throws a security exception.</p>
    773 
    774 <p>To request the licensing permission in your application, declare a <a
    775 href="{@docRoot}guide/topics/manifest/uses-permission-element.html"><code>&lt;uses-permission&gt;</code></a>
    776 element as a child of <code>&lt;manifest&gt;</code>, as follows: </p>
    777 
    778 <p style="margin-left:2em;"><code>&lt;uses-permission
    779 android:name="com.android.vending.CHECK_LICENSE"&gt;</code></p>
    780 
    781 <p>For example, here's how the LVL sample application declares the permission:
    782 </p>
    783 
    784 <pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;
    785 
    786 &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" ..."&gt;
    787     ...
    788     &lt;!-- Devices &gt;= 3 have version of Android Market that supports licensing. --&gt;
    789     &lt;uses-sdk android:minSdkVersion="3" /&gt;
    790     &lt;!-- Required permission to check licensing. --&gt;
    791     &lt;uses-permission android:name="com.android.vending.CHECK_LICENSE" /&gt;
    792     ...
    793 &lt;/manifest&gt;
    794 </pre>
    795 
    796 <p class="note"><strong>Note:</strong> Currently, you cannot declare the
    797 <code>CHECK_LICENSE</code> permission in the LVL library project's manifest,
    798 because the SDK Tools will not merge it into the manifests of dependent
    799 applications. Instead, you must declare the permission in each dependent
    800 application's manifest. </p>
    801 
    802 
    803 <h3 id="impl-Policy">Implementing a Policy</h3>
    804 
    805 <div class="sidebox-wrapper">
    806 <div class="sidebox">
    807 <h2>ServerManagedPolicy</h2>
    808 
    809 <p>The LVL includes a complete Policy implementation called ServerManagedPolicy
    810 that makes use of license-management settings provided by the Android Market
    811 server. </p>
    812 
    813 <p style="margin-top:.5em;">Use of ServerManagedPolicy as the basis for your
    814 Policy is strongly recommended. For more information, see <a
    815 href="#ServerManagedPolicy">ServerManagedPolicy</a> section, below.</p>
    816 
    817 </div>
    818 </div>
    819 
    820 <p>Android Market licensing service does not itself determine whether a
    821 given user with a given license should be granted access to your application.
    822 Rather, that responsibility is left to a Policy implementation that you provide
    823 in your application.</p>
    824 
    825 <p>Policy is an interface declared by the LVL that is designed to hold your
    826 application's logic for allowing or disallowing user access, based on the result
    827 of a license check. To use the LVL, your application <em>must</em> provide an
    828 implementation of Policy. </p>
    829 
    830 <p>The Policy interface declares two methods, <code>allowAccess()</code> and
    831 <code>processServerResponse()</code>, which are called by a LicenseChecker
    832 instance when processing a response from the license server. It also declares an
    833 enum called <code>LicenseResponse</code>, which specifies the license response
    834 value passed in calls to <code>processServerResponse()</code>. </p>
    835 
    836 <ul>
    837 <li><code>processServerResponse()</code> lets you preprocess the raw response
    838 data received from the licensing server, prior to determining whether to grant
    839 access.
    840 
    841 <p>A typical implementation would extract some or all fields from the license
    842 response and store the data locally to a persistent store, such as through
    843 {@link android.content.SharedPreferences} storage, to ensure that the data is
    844 accessible across application invocations and device power cycles. For example,
    845 a Policy would maintain the timestamp of last successful license check, the
    846 retry count, the license validity period, and similar information in a
    847 persistent store, rather than resetting the values each time the application is
    848 launched.</p>
    849 
    850 <p>When storing response data locally, the Policy must ensure that the data is
    851 obfuscated (see <a href="#impl-Obfuscator">Implementing an Obfuscator</a>,
    852 below).</p></li>
    853 
    854 <li><code>allowAccess()</code> determines whether to grant the user access to
    855 your application, based on any available license response data (from the
    856 licensing server or from cache) or other application-specific information.  For
    857 example, your implementation of <code>allowAccess()</code> could take into
    858 account additional criteria, such as usage or other data retrieved from a
    859 backend server. In all cases, an implementation of <code>allowAccess()</code>
    860 should only return <code>true</code> if the user is licensed to use the
    861 application, as determined by the licensing server, or if there is a transient
    862 network or system problem that prevents the license check from completing. In
    863 such cases, your implementation can maintain a count of retry responses and
    864 provisionally allow access until the next license check is complete.</li>
    865 
    866 </ul>
    867 
    868 <p>To simplify the process of adding licensing to your application and to
    869 provide an illustration of how a Policy should be designed, the LVL includes
    870 two full Policy implementations that you can use without modification or
    871 adapt to your needs:</p>
    872 
    873 <ul>
    874 <li><a href="#ServerManagedPolicy">ServerManagedPolicy</a>, a flexible Policy
    875 that uses server-provided settings and cached responses to manage access across
    876 varied network conditions, and</li>
    877 <li><a href="#StrictPolicy">StrictPolicy</a>, which does not cache any response
    878 data and allows access <em>only</em> if the server returns a licensed
    879 response.</li>
    880 </ul>
    881 
    882 <p>For most applications, the use of ServerManagedPolicy is highly
    883 recommended. ServerManagedPolicy is the LVL default and is integrated with
    884 the LVL sample application.</p>
    885 
    886 
    887 <h4 id="custom-policies">Guidelines for custom policies</h4>
    888 
    889 <p>In your licensing implementation, you can use one of the complete policies
    890 provided in the LVL (ServerManagedPolicy or StrictPolicy) or you can create a
    891 custom policy. For any type of custom policy, there are several important design
    892 points to understand and account for in your implementation.</p>
    893 
    894 <p>The licensing server applies general request limits to guard against overuse
    895 of resources that could result in denial of service. When an application exceeds
    896 the request limit, the licensing server returns a 503 response, which gets
    897 passed through to your application as a general server error. This means that no
    898 license response will be available to the user until the limit is reset, which
    899 can affect the user for an indefinite period.</p>
    900 
    901 <p>If you are designing a custom policy, we recommend that the Policy:
    902 <ol>
    903 <!-- <li>Limits the number of points at which your app calls for a license check
    904 to the minimum. </li> -->
    905 <li>Caches (and properly obfuscates) the most recent successful license response
    906 in local persistent storage.</li>
    907 <li>Returns the cached response for all license checks, for as long as the
    908 cached response is valid, rather than making a request to the licensing server.
    909 Setting the response validity according to the server-provided <code>VT</code>
    910 extra is highly recommended. See <a href="#extras">Server Response Extras</a>
    911 for more information.</li>
    912 <li>Uses an exponential backoff period, if retrying any requests the result in
    913 errors. Note that the Android Market client automatically retries failed
    914 requests, so in most cases there is no need for your Policy to retry them.</li>
    915 <li>Provides for a "grace period" that allows the user to access your
    916 application for a limited time or number of uses, while a license check is being
    917 retried. The grace period benefits the user by allowing access until the next
    918 license check can be completed successfully and it benefits you by placing a
    919 hard limit on access to your application when there is no valid license response
    920 available.</li>
    921 </ol>
    922 
    923 <p>Designing your Policy according to the guidelines listed above is critical,
    924 because it ensures the best possible experience for users while giving you
    925 effective control over your application even in error conditions. </p>
    926 
    927 <p>Note that any Policy can use settings provided by the licensing server to
    928 help manage validity and caching, retry grace period, and more. Extracting the
    929 server-provided settings is straightforward and making use of them is highly
    930 recommended. See the ServerManagedPolicy implementation for an example of how to
    931 extract and use the extras. For a list of server settings and information about
    932 how to use them, see  <a href="#extras">Server Response Extras</a> in the
    933 Appendix of this document.</p>
    934 
    935 <h4 id="ServerManagedPolicy">ServerManagedPolicy</h4>
    936 
    937 <div class="sidebox-wrapper">
    938 <div class="sidebox">
    939 <h2>Server Response Extras</h2>
    940 
    941 <p>For certain types of licensing responses, the licensing server appends extra
    942 settings to the responses, to help the application manage licensing effectively.
    943 </p>
    944 
    945 <p style="margin-top:.5em;">See <a href="#extras">Server Response Extras</a> for
    946 a list of settings and <code>ServerManagedPolicy.java</code> for information
    947 about how a Policy can use the extras.</p>
    948 
    949 </div>
    950 </div>
    951 
    952 <p>The LVL includes a full and recommended implementation of the Policy
    953 interface called ServerManagedPolicy. The implementation is integrated with the
    954 LVL classes and serves as the default Policy in the library. </p>
    955 
    956 <p>ServerManagedPolicy provides all of the handling for license and retry
    957 responses. It caches all of the response data locally in a
    958 {@link android.content.SharedPreferences} file, obfuscating it with the
    959 application's Obfuscator implementation. This ensures that the license response
    960 data is secure and persists across device power cycles. ServerManagedPolicy
    961 provides concrete implementations of the interface methods
    962 <code>processServerResponse()</code> and <code>allowAccess()</code> and also
    963 includes a set of supporting methods and types for managing license
    964 responses.</p>
    965 
    966 <p>Importantly, a key feature of ServerMangedPolicy is its use of
    967 server-provided settings as the basis for managing licensing across an
    968 application's refund period and through varying network and error conditions.
    969 When an application contacts the Android Market server for a license check, the
    970 server appends several settings as key-value pairs in the extras field of certain
    971 license response types. For example, the server provides recommended values for the
    972 application's license validity period, retry grace period, and maximum allowable
    973 retry count, among others. ServerManagedPolicy extracts the values from the
    974 license response in its <code>processServerResponse()</code> method and checks
    975 them in its <code>allowAccess()</code> method. For a list of the server-provided
    976 settings used by ServerManagedPolicy, see <a href="#extras">Server Response
    977 Extras</a> in the Appendix of this document.</p>
    978 
    979 <p>For convenience, best performance, and the benefit of using license settings
    980 from the Android Market server, <strong>using ServerManagedPolicy as your
    981 licensing Policy is strongly recommended</strong>. </p>
    982 
    983 <p>If you are concerned about the security of license response data that is
    984 stored locally in SharedPreferences, you can use a stronger obfuscation
    985 algorithm or design a stricter Policy that does not store license data. The LVL
    986 includes an example of such a Policy &mdash; see <a
    987 href="#StrictPolicy">StrictPolicy</a> for more information.</p>
    988 
    989 <p>To use ServerManagedPolicy, simply import it to your Activity, create an
    990 instance, and pass a reference to the instance when constructing your
    991 LicenseChecker. See <a href="#lc-lcc">Instantiate LicenseChecker and
    992 LicenseCheckerCallback</a> for more information. </p>
    993 
    994 <h4 id="StrictPolicy">StrictPolicy</h4>
    995 
    996 <p>The LVL includes an alternative full implementation of the Policy interface
    997 called StrictPolicy. The StrictPolicy implementation provides a more restrictive
    998 Policy than ServerManagedPolicy, in that it does not allow the user to access
    999 the application unless a license response is received from the server at the
   1000 time of access that indicates that the user is licensed.</p>
   1001 
   1002 <p>The principal feature of StrictPolicy is that it does not store <em>any</em>
   1003 license response data locally, in a persistent store. Because no data is stored,
   1004 retry requests are not tracked and cached responses can not be used to fulfill
   1005 license checks. The Policy allows access only if:</p>
   1006 
   1007 <ul>
   1008 <li>The license response is received from the licensing server, and </li>
   1009 <li>The license response indicates that the user is licensed to access the
   1010 application. </li>
   1011 </ul>
   1012 
   1013 <p>Using StrictPolicy is appropriate if your primary concern is to ensure that,
   1014 in all possible cases, no user will be allowed to access the application unless
   1015 the user is confirmed to be licensed at the time of use. Additionally, the
   1016 Policy offers slightly more security than ServerManagedPolicy &mdash; since
   1017 there is no data cached locally, there is no way a malicious user could tamper
   1018 with the cached data and obtain access to the application.</p>
   1019 
   1020 <p>At the same time, this Policy presents a challenge for normal users, since it
   1021 means that they won't be able to access the application when there is no network
   1022 (cell or wi-fi) connection available. Another side-effect is that your
   1023 application will send more license check requests to the server, since using a
   1024 cached response is not possible.</p>
   1025 
   1026 <p>Overall, this policy represents a tradeoff of some degree of user convenience
   1027 for absolute security and control over access. Consider the tradeoff carefully
   1028 before using this Policy.</p>
   1029 
   1030 <p>To use StrictPolicy, simply import it to your Activity, create an instance,
   1031 and pass a reference to it when constructing your LicenseChecker. See
   1032 <a href="#lc-lcc">Instantiate LicenseChecker and LicenseCheckerCallback</a>
   1033 for more information. </p>
   1034 
   1035 <h3 id="impl-Obfuscator">Implementing an Obfuscator</h3>
   1036 
   1037 <div class="sidebox-wrapper">
   1038 <div class="sidebox">
   1039 <h2>AESObfuscator</h2>
   1040 
   1041 <p>The LVL includes a full Obfuscator implementation in the
   1042 <code>AESObfuscator.java</code> file. The Obfuscator uses AES encryption to
   1043 obfuscate/unobfuscate data. If you are using a Policy (such as
   1044 ServerManagedPolicy) that caches license response data, using AESObfuscator as
   1045 basis for your Obfuscator implementation is highly recommended. </p>
   1046 
   1047 </div>
   1048 </div>
   1049 
   1050 <p>A typical Policy implementation needs to save the license response data for
   1051 an application to a persistent store, so that it is accessible across
   1052 application invocations and device power cycles.  For example, a Policy would
   1053 maintain the timestamp of the last successful license check, the retry count,
   1054 the license validity period, and similar information in a persistent store,
   1055 rather than resetting the values each time the application is launched. The
   1056 default Policy included in the LVL, ServerManagedPolicy, stores license response
   1057 data in a {@link android.content.SharedPreferences} instance, to ensure that the
   1058 data is persistent. </p>
   1059 
   1060 <p>Because the Policy will use stored license response data to determine whether
   1061 to allow or disallow access to the application, it <em>must</em> ensure that any
   1062 stored data is secure and cannot be reused or manipulated by a root user on a
   1063 device. Specifically, the Policy must always obfuscate the data before storing
   1064 it, using a key that is unique for the application and device. Obfuscating using
   1065 a key that is both application-specific and device-specific is critical, because
   1066 it prevents the obfuscated data from being shared among applications and
   1067 devices.</p>
   1068 
   1069 <p>The LVL assists the application with storing its license response data in a
   1070 secure, persistent manner. First, it provides an Obfuscator
   1071 interface that lets your application supply the obfuscation algorithm of its
   1072 choice for stored data. Building on that, the LVL provides the helper class
   1073 PreferenceObfuscator, which handles most of the work of calling the
   1074 application's Obfuscator class and reading and writing the obfuscated data in a
   1075 SharedPreferences instance. </p>
   1076 
   1077 <p>The LVL provides a full Obfuscator implementation called
   1078 AESObfuscator that uses AES encryption to obfuscate data. You can
   1079 use AESObfuscator in your application without modification or you
   1080 can adapt it to your needs. For more information, see the next section.</p>
   1081 
   1082 
   1083 <h4 id="AESObfuscator">AESObfuscator</h4>
   1084 
   1085 <p>The LVL includes a full and recommended implementation of the Obfuscator
   1086 interface called AESObfuscator. The implementation is integrated with the
   1087 LVL sample application and serves as the default Obfuscator in the library. </p>
   1088 
   1089 <p>AESObfuscator provides secure obfuscation of data by using AES to
   1090 encrypt and decrypt the data as it is written to or read from storage.
   1091 The Obfuscator seeds the encryption using three data fields provided
   1092 by the application: </p>
   1093 
   1094 <ol>
   1095 <li>A salt &mdash; an array of random bytes to use for each (un)obfuscation. </li>
   1096 <li>An application identifier string, typically the package name of the application.</li>
   1097 <li>A device identifier string, derived from as many device-specific sources
   1098 as possible, so as to make it as unique.</li>
   1099 </ol>
   1100 
   1101 <p>To use AESObfuscator, first import it to your Activity. Declare a private
   1102 static final array to hold the salt bytes and initialize it to 20 randomly
   1103 generated bytes.</p>
   1104 
   1105 <pre>    ...
   1106     // Generate 20 random bytes, and put them here.
   1107     private static final byte[] SALT = new byte[] {
   1108      -46, 65, 30, -128, -103, -57, 74, -64, 51, 88, -95,
   1109      -45, 77, -117, -36, -113, -11, 32, -64, 89
   1110      };
   1111     ...
   1112 </pre>
   1113 
   1114 <p>Next, declare a variable to hold a device identifier and generate a value for
   1115 it in any way needed. For example, the sample application included in the LVL
   1116 queries the system settings for the
   1117 <code>android.Settings.Secure.ANDROID_ID</code>, which is unique to each device.
   1118 </p>
   1119 
   1120 <p>Note that, depending on the APIs you use, your application might need to
   1121 request additional permissions in order to acquire device-specific information.
   1122 For example, to query the {@link android.telephony.TelephonyManager} to obtain
   1123 the device IMEI or related data, the application will also need to request the
   1124 <code>android.permission.READ_PHONE_STATE</code> permission in its manifest.</p>
   1125 
   1126 <p>Before requesting new permissions for the <em>sole purpose</em> of acquiring
   1127 device-specific information for use in your Obfuscator, consider
   1128 how doing so might affect your application or its filtering on Android Market
   1129 (since some permissions can cause the SDK build tools to add
   1130 the associated <code>&lt;uses-feature&gt;</code>).</p>
   1131 
   1132 <p>Finally, construct an instance of AESObfuscator, passing the salt,
   1133 application identifier, and device identifier. You can construct the instance
   1134 directly, while constructing your Policy and LicenseChecker. For example:</p>
   1135 
   1136 <pre>    ...
   1137     // Construct the LicenseChecker with a Policy.
   1138     mChecker = new LicenseChecker(
   1139         this, new ServerManagedPolicy(this,
   1140             new AESObfuscator(SALT, getPackageName(), deviceId)),
   1141         BASE64_PUBLIC_KEY  // Your public licensing key.
   1142         );
   1143     ...
   1144 </pre>
   1145 
   1146 <p>For a complete example, see MainActivity in the LVL sample application.</p>
   1147 
   1148 
   1149 <h3 id="impl-lc">Checking the license from your application's main Activity</h3>
   1150 
   1151 <p>Once you've implemented a Policy for managing access to your application, the
   1152 next step is to add a license check to your application, which initiates a query
   1153 to the licensing server if needed and manages access to the application based on
   1154 the license response. All of the work of adding the license check and handling
   1155 the response takes place in your main {@link android.app.Activity} source file.
   1156 </p>
   1157 
   1158 <p>To add the license check and handle the response, you must:</p>
   1159 
   1160 <ol>
   1161     <li><a href="#imports">Add imports</a></li>
   1162     <li><a href="#lc-impl">Implement LicenseCheckerCallback</a> as a private inner class</li>
   1163     <li><a href="#thread-handler">Create a Handler</a> for posting from LicenseCheckerCallback to the UI thread</li>
   1164     <li><a href="#lc-lcc">Instantiate LicenseChecker</a> and LicenseCheckerCallback</li>
   1165     <li><a href="#check-access">Call checkAccess()</a> to initiate the license check</li>
   1166     <li><a href="#account-key">Embed your public key</a> for licensing</li>
   1167     <li><a href="#handler-cleanup">Call your LicenseChecker's onDestroy() method</a> to close IPC connections.</li>
   1168 </ol>
   1169 
   1170 <p>The sections below describe these tasks. </p>
   1171 
   1172 <h4 id="lc-overview">Overview of license check and response</h4>
   1173 
   1174 <div class="sidebox-wrapper">
   1175 <div class="sidebox">
   1176 <h2>Example: MainActivity</h2>
   1177 
   1178 <p>The sample application included with the LVL provides a full example of how
   1179 to initiate a license check and handle the result, in the
   1180 <code>MainActivity.java</code> file.</p>
   1181 
   1182 </div>
   1183 </div>
   1184 
   1185 <p>In most cases, you should add the license check to your application's main
   1186 {@link android.app.Activity}, in the <code>onCreate()</code> method. This
   1187 ensures that when the user launches your application directly, the license check
   1188 will be invoked immediately. In some cases, you can add license checks in other
   1189 locations as well. For example, if your application includes multiple Activity
   1190 components that other applications can start by {@link android.content.Intent},
   1191 you could add license checks in those Activities.</p>
   1192 
   1193 <p>A license check consists of two main actions: </p>
   1194 
   1195 <ul>
   1196 <li>A call to a method to initiate the license check &mdash; in the LVL, this is
   1197 a call to the <code>checkAccess()</code> method of a LicenseChecker object that
   1198 you construct.</li>
   1199 <li>A callback that returns the result of the license check. In the LVL, this is
   1200 a <code>LicenseCheckerCallback</code> interface that you implement. The
   1201 interface declares two methods, <code>allow()</code> and
   1202 <code>dontAllow()</code>, which are invoked by the library based on to the
   1203 result of the license check. You implement those two methods with whatever logic
   1204 you need, to allow or disallow the user access to your application. Note that
   1205 these methods do not determine <em>whether</em> to allow access &mdash; that
   1206 determination is the responsibility of your Policy implementation. Rather, these
   1207 methods simply provide the application behaviors for <em>how</em> to allow and
   1208 disallow access (and handle application errors).</li>
   1209 </ul>
   1210 
   1211 <div style="margin-bottom:2em;">
   1212 
   1213 <img src="{@docRoot}images/licensing_flow.png" style="text-align:left;margin-bottom:0;margin-left:3em;" />
   1214 <div style="margin:.5em 0 1.5em 2em;padding:0"><strong>Figure 6.</strong> Overview of a
   1215 typical license check interaction.</div>
   1216 </div>
   1217 
   1218 <p>The diagram above illustrates how a typical license check takes place: </p>
   1219 
   1220 <ol>
   1221 <li>Code in the application's main Activity instantiates LicenseCheckerCallback
   1222 and LicenseChecker objects. When constructing LicenseChecker, the code passes in
   1223 {@link android.content.Context}, a Policy implementation to use, and the
   1224 publisher account's public key for licensing as parameters. </li>
   1225 <li>The code then calls the <code>checkAccess()</code> method on the
   1226 LicenseChecker object. The method implementation calls the Policy to determine
   1227 whether there is a valid license response cached locally, in
   1228 {@link android.content.SharedPreferences}.
   1229 <ul>
   1230 <li>If so, the <code>checkAccess()</code> implementation calls
   1231 <code>allow()</code>.</li>
   1232 <li>Otherwise, the LicenseChecker initiates a license check request that is sent
   1233 to the licensing server.</li>
   1234 </ul>
   1235 </li>
   1236 <li>When a response is received, LicenseChecker creates a LicenseValidator that
   1237 verifies the signed license data and extracts the fields of the response, then
   1238 passes them to your Policy for further evaluation.
   1239   <ul>
   1240     <li>If the license is valid, the Policy caches the response in
   1241 SharedPreferences and notifies the validator, which then calls the
   1242 <code>allow()</code> method on the LicenseCheckerCallback object. </li>
   1243     <li>If the license not valid, the Policy notifies the validator, which calls
   1244 the <code>dontAllow()</code> method on LicenseCheckerCallback. </li>
   1245   </ul>
   1246 </li>
   1247 <li>In case of a recoverable local or server error, such as when the network is
   1248 not available to send the request, LicenseChecker passes a RETRY response to
   1249 your Policy's <code>processServerResponse()</code> method. </li>
   1250 <li>In case of a application error, such as when the application attempts to
   1251 check the license of an invalid package name, LicenseChecker passes an error
   1252 response to the LicenseCheckerCallback's  <code>applicationError()</code>
   1253 method. </li>
   1254 </ol>
   1255 
   1256 <p>Note that, in addition to initiating the license check and handling the
   1257 result, which are described in the sections below, your application also needs
   1258 to provide a <a href="#impl-Policy">Policy implementation</a> and, if the Policy
   1259 stores response data (such as ServerManagedPolicy), an <a
   1260 href="#impl-Obfuscator">Obfuscator</a> implementation. </p>
   1261 
   1262 
   1263 <h4 id="imports">Add imports</h4>
   1264 
   1265 <p>First, open the class file of the application's main Activity and import
   1266 LicenseChecker and LicenseCheckerCallback from the LVL package.</p>
   1267 
   1268 <pre>    import com.android.vending.licensing.LicenseChecker;
   1269     import com.android.vending.licensing.LicenseCheckerCallback;</pre>
   1270 
   1271 <p>If you are using the default Policy implementation provided with the LVL,
   1272 ServerManagedPolicy, import it also, together with the AESObfuscator. If you are
   1273 using a custom Policy or Obfuscator, import those instead. </p>
   1274 
   1275 <pre>    import com.android.vending.licensing.ServerManagedPolicy;
   1276     import com.android.vending.licensing.AESObfuscator;</pre>
   1277 
   1278 <h4 id="lc-impl">Implement LicenseCheckerCallback as a private inner class</h4>
   1279 
   1280 <p>LicenseCheckerCallback is an interface provided by the LVL for handling
   1281 result of a license check. To support licensing using the LVL, you must
   1282 implement LicenseCheckerCallback and
   1283 its methods to allow or disallow access to the application.</p>
   1284 
   1285 <p>The result of a license check is always a call to one of the
   1286 LicenseCheckerCallback methods, made based on the validation of the response
   1287 payload, the server response code itself, and any additional processing provided
   1288 by your Policy. Your application can implement the methods in any way needed. In
   1289 general, it's best to keep the methods simple, limiting them to managing UI
   1290 state and application access. If you want to add further processing of license
   1291 responses, such as by contacting a backend server or applying custom constraints,
   1292 you should consider incorporating that code into your Policy, rather than
   1293 putting it in the LicenseCheckerCallback methods. </p>
   1294 
   1295 <p>In most cases, you should declare your implementation of
   1296 LicenseCheckerCallback as a private class inside your application's main
   1297 Activity class. </p>
   1298 
   1299 <p>Implement the <code>allow()</code> and <code>dontAllow()</code> methods as
   1300 needed. To start with, you can use simple result-handling behaviors in the
   1301 methods, such as displaying the license result in a dialog. This helps you get
   1302 your application running sooner and can assist with debugging. Later, after you
   1303 have determined the exact behaviors you want, you can add more complex handling.
   1304 </p>
   1305 
   1306 <p>Some suggestions for handling unlicensed responses in
   1307 <code>dontAllow()</code> include: </p>
   1308 
   1309 <ul>
   1310 <li>Display a "Try again" dialog to the user, including a button to initiate a
   1311 new license check. </li>
   1312 <li>Display a "Purchase this application" dialog, including a button that
   1313 deep-links the user to the application's details page on Market, from which the
   1314 use can purchase the application. For more information on how to set up such
   1315 links, see <a
   1316 href="{@docRoot}guide/publishing/publishing.html#marketintent">Using Intents to
   1317 Launch the Market Application on a Device</a>. </li>
   1318 <li>Display a Toast notification that indicates that the features of the
   1319 application are limited because it is not licensed. </li>
   1320 </ul>
   1321 
   1322 <p>The example below shows how the LVL sample application implements
   1323 LicenseCheckerCallback, with methods that display the license check result in a
   1324 dialog. </p>
   1325 
   1326 <pre>    private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
   1327         public void allow() {
   1328             if (isFinishing()) {
   1329                 // Don't update UI if Activity is finishing.
   1330                 return;
   1331             }
   1332             // Should allow user access.
   1333             displayResult(getString(R.string.allow));
   1334         }
   1335 
   1336         public void dontAllow() {
   1337             if (isFinishing()) {
   1338                 // Don't update UI if Activity is finishing.
   1339                 return;
   1340             }
   1341             displayResult(getString(R.string.dont_allow));
   1342             // Should not allow access. An app can handle as needed,
   1343             // typically by informing the user that the app is not licensed
   1344             // and then shutting down the app or limiting the user to a
   1345             // restricted set of features.
   1346             // In this example, we show a dialog that takes the user to Market.
   1347             showDialog(0);
   1348         }
   1349     }
   1350 </pre>
   1351 
   1352 <p>Additionally, you should implement the <code>applicationError()</code>
   1353 method, which the LVL calls to let your application handle errors that are not
   1354 retryable. For a list of such errors, see <a
   1355 href="#server-response-codes">Server Response Codes</a> in the Appendix of this
   1356 document. You can implement the method in any way needed. In most cases, the
   1357 method should log the error code and call <code>dontAllow()</code>.</p>
   1358 
   1359 <h4 id="thread-handler">Create a Handler for posting from LicenseCheckerCallback
   1360 to the UI thread</h4>
   1361 
   1362 <p>During a license check, the LVL passes the request to the Android Market
   1363 application, which handles communication with the licensing server. The LVL
   1364 passes the request over asynchronous IPC (using {@link android.os.Binder}) so
   1365 the actual processing and network communication do not take place on a thread
   1366 managed by your application. Similarly, when the Android Market application
   1367 receives the result, it invokes a  callback method over IPC, which in turn
   1368 executes in an IPC thread pool in your application's process.</p>
   1369 
   1370 <p>The LicenseChecker class manages your application's IPC communication with
   1371 the Android Market application, including the call that sends the request and
   1372 the callback that receives the response. LicenseChecker also tracks open license
   1373 requests and manages their timeouts. </p>
   1374 
   1375 <p>So that it can handle timeouts properly and also process incoming responses
   1376 without affecting your application's UI thread, LicenseChecker spawns a
   1377 background thread at instantiation. In the thread it does all processing of
   1378 license check results, whether the result is a response received from the server
   1379 or a timeout error. At the conclusion of processing, the LVL calls your
   1380 LicenseCheckerCallback methods from the background thread. </p>
   1381 
   1382 <p>To your application, this means that:</p>
   1383 
   1384 <ol>
   1385 <li>Your LicenseCheckerCallback methods will be invoked, in many cases, from a
   1386 background thread.</li>
   1387 <li>Those methods won't be able to update state or invoke any processing in the
   1388 UI thread, unless you create a Handler in the UI thread and have your callback
   1389 methods post to the Handler.</li>
   1390 </ol>
   1391 
   1392 <p>If you want your LicenseCheckerCallback methods to update the UI thread,
   1393 instantiate a {@link android.os.Handler} in the main Activity's 
   1394 {@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method,
   1395 as shown below. In this example, the LVL sample application's
   1396 LicenseCheckerCallback methods (see above) call <code>displayResult()</code> to
   1397 update the UI thread through the Handler's
   1398 {@link android.os.Handler#post(java.lang.Runnable) post()} method.</p>
   1399 
   1400 <pre>private Handler mHandler;
   1401 
   1402     &#64;Override
   1403     public void onCreate(Bundle savedInstanceState) {
   1404         ...
   1405         mHandler = new Handler();
   1406     }
   1407 </pre>
   1408 
   1409 <p>Then, in your LicenseCheckerCallback methods, you can use Handler methods to
   1410 post Runnable or Message objects to the Handler. Here's how the sample
   1411 application included in the LVL posts a Runnable to a Handler in the UI thread
   1412 to display the license status.</p>
   1413 
   1414 <pre>    private void displayResult(final String result) {
   1415         mHandler.post(new Runnable() {
   1416             public void run() {
   1417                 mStatusText.setText(result);
   1418                 setProgressBarIndeterminateVisibility(false);
   1419                 mCheckLicenseButton.setEnabled(true);
   1420             }
   1421         });
   1422     }
   1423 </pre>
   1424 
   1425 <h4 id="lc-lcc">Instantiate LicenseChecker and LicenseCheckerCallback</h4>
   1426 
   1427 <p>In the main Activity's
   1428 {@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method,
   1429 create private instances of LicenseCheckerCallback and LicenseChecker. You must
   1430 instantiate LicenseCheckerCallback first, because you need to pass a reference
   1431 to that instance when you call the contructor for LicenseChecker. </p>
   1432 
   1433 <p>When you instantiate LicenseChecker, you need to pass in these parameters:</p>
   1434 
   1435 <ul>
   1436 <li>The application {@link android.content.Context}</li>
   1437 <li>A reference to the Policy implementation to use for the license check. In
   1438 most cases, you would use the default Policy implementation provided by the LVL,
   1439 ServerManagedPolicy. </li>
   1440 <li>The String variable holding your publisher account's public key for
   1441 licensing. </li>
   1442 </ul>
   1443 
   1444 <p>If you are using ServerManagedPolicy, you won't need to access the class
   1445 directly, so you can instantiate it in the LicenseChecker constructor,
   1446 as shown in the example below. Note that you need to pass a reference to a new
   1447 Obfuscator instance when you construct ServerManagedPolicy.</p>
   1448 
   1449 <p>The example below shows the instantiation of LicenseChecker and
   1450 LicenseCheckerCallback from the <code>onCreate()</code> method of an Activity
   1451 class. </p>
   1452 
   1453 <pre>public class MainActivity extends Activity {
   1454     ...
   1455     private LicenseCheckerCallback mLicenseCheckerCallback;
   1456     private LicenseChecker mChecker;
   1457 
   1458     &#64;Override
   1459     public void onCreate(Bundle savedInstanceState) {
   1460         super.onCreate(savedInstanceState);
   1461         ...
   1462         // Construct the LicenseCheckerCallback. The library calls this when done.
   1463         mLicenseCheckerCallback = new MyLicenseCheckerCallback();
   1464 
   1465         // Construct the LicenseChecker with a Policy.
   1466         mChecker = new LicenseChecker(
   1467             this, new ServerManagedPolicy(this,
   1468                 new AESObfuscator(SALT, getPackageName(), deviceId)),
   1469             BASE64_PUBLIC_KEY  // Your public licensing key.
   1470             );
   1471         ...
   1472     }
   1473 }
   1474 </pre>
   1475 
   1476 
   1477 <p>Note that LicenseChecker calls the LicenseCheckerCallback methods from the UI
   1478 thread <em>only</em> if there is valid license response cached locally. If the
   1479 license check is sent to the server, the callbacks always originate from the
   1480 background thread, even for network errors. </p>
   1481 
   1482 
   1483 <h4 id="check-access">Call checkAccess() to initiate the license check</h4>
   1484 
   1485 <p>In your main Activity, add a call to the <code>checkAccess()</code> method of the
   1486 LicenseChecker instance. In the call, pass a reference to your
   1487 LicenseCheckerCallback instance as a parameter. If you need to handle any
   1488 special UI effects or state management before the call, you might find it useful
   1489 to call <code>checkAccess()</code> from a wrapper method. For example, the LVL
   1490 sample application calls <code>checkAccess()</code> from a
   1491 <code>doCheck()</code> wrapper method:</p>
   1492 
   1493 <pre>    &#64;Override
   1494     public void onCreate(Bundle savedInstanceState) {
   1495         super.onCreate(savedInstanceState);
   1496         ...
   1497         // Call a wrapper method that initiates the license check
   1498         doCheck();
   1499         ...
   1500     }
   1501     ...
   1502     private void doCheck() {
   1503         mCheckLicenseButton.setEnabled(false);
   1504         setProgressBarIndeterminateVisibility(true);
   1505         mStatusText.setText(R.string.checking_license);
   1506         mChecker.checkAccess(mLicenseCheckerCallback);
   1507     }
   1508 </pre>
   1509 
   1510 
   1511 <h4 id="account-key">Embed your public key for licensing</h4>
   1512 
   1513 <p>For each publisher account, the Android Market service automatically
   1514 generates a  2048-bit RSA public/private key pair that is used exclusively for
   1515 licensing. The key pair is uniquely associated with the publisher account and is
   1516 shared across all applications that are published through the account. Although
   1517 associated with a publisher account, the key pair is <em>not</em> the same as
   1518 the key that you use to sign your applications (or derived from it).</p>
   1519 
   1520 <p>The Android Market publisher site exposes the public key for licensing to any
   1521 developer signed in to the publisher account, but it keeps the private key
   1522 hidden from all users in a secure location. When an application requests a
   1523 license check for an application published in your account, the licensing server
   1524 signs the license response using the private key of your account's key pair.
   1525 When the LVL receives the response, it uses the public key provided by the
   1526 application to verify the signature of the license response. </p>
   1527 
   1528 <p>To add licensing to an application, you must obtain your publisher account's
   1529 public key for licensing and copy it into your application. Here's how to find
   1530 your account's public key for licensing:</p>
   1531 
   1532 <ol>
   1533 <li>Go to the Android Market <a
   1534 href="http://market.android.com/publish">publisher site</a> and sign in.
   1535 Make sure that you sign in to the account from which the application you are
   1536 licensing is published (or will be published). </li>
   1537 <li>In the account home page, locate the "Edit profile" link and click it. </li>
   1538 <li>In the Edit Profile page, locate the "Licensing" pane, shown below. Your
   1539 public key for licensing is given in the "Public key" text box. </p>
   1540 </ol>
   1541 
   1542 <p>To add the public key to your application, simply copy/paste the key string
   1543 from the text box into your application as the value of the String variable
   1544 <code>BASE64_PUBLIC_KEY</code>. When you are copying, make sure that you have
   1545 selected the entire key string, without omitting any characters. </p>
   1546 
   1547 <p>Here's an example from the LVL sample application:</p>
   1548 
   1549 <pre>    public class MainActivity extends Activity {
   1550         private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG ... "; //truncated for this example
   1551     ...
   1552     }
   1553 </pre>
   1554 
   1555 <h4 id="handler-cleanup">Call your LicenseChecker's onDestroy() method
   1556 to close IPC connections</h4>
   1557 
   1558 <p>Finally, to let the LVL clean up before your application
   1559 {@link android.content.Context} changes, add a call to the LicenseChecker's
   1560 <code>onDestroy()</code> method from your Activity's
   1561 {@link android.app.Activity#onDestroy()} implementation. The call causes the
   1562 LicenseChecker to properly close any open IPC connection to the Android Market
   1563 application's ILicensingService and removes any local references to the service
   1564 and handler.</p>
   1565 
   1566 <p>Failing to call the LicenseChecker's <code>onDestroy()</code> method
   1567 can lead to problems over the lifecycle of your application. For example, if the
   1568 user changes screen orientation while a license check is active, the application
   1569 {@link android.content.Context} is destroyed. If your application does not
   1570 properly close the LicenseChecker's IPC connection, your application will crash
   1571 when the response is received. Similarly, if the user exits your application
   1572 while a license check is in progress,  your application will crash when the
   1573 response is received, unless it has properly called the
   1574 LicenseChecker's <code>onDestroy()</code> method to disconnect from the service.
   1575 </p>
   1576 
   1577 <p>Here's an example from the sample application included in the LVL, where
   1578 <code>mChecker</code> is the LicenseChecker instance:</p>
   1579 
   1580 <pre>    &#64;Override
   1581     protected void onDestroy() {
   1582         super.onDestroy();
   1583         mChecker.onDestroy();
   1584         ...
   1585     }
   1586 </pre>
   1587 
   1588 <p>If you are extending or modifying LicenseChecker, you might also need to call
   1589 the LicenseChecker's <code>finishCheck()</code> method, to clean up any open IPC
   1590 connections.</p>
   1591 
   1592 <h3 id="impl-DeviceLimiter">Implementing a DeviceLimiter</h3>
   1593 
   1594 <p>In some cases, you might want your Policy to limit the number of actual
   1595 devices that are permitted to use a single license. This would prevent a user
   1596 from moving a licensed application onto a number of devices and using the
   1597 application on those devices under the same account ID. It would also prevent a
   1598 user from "sharing" the application by providing the account information
   1599 associated with the license to other individuals, who could then sign in to that
   1600 account on their devices and access the license to the application. </p>
   1601 
   1602 <p>The LVL supports per-device licensing by providing a
   1603 <code>DeviceLimiter</code> interface, which declares a single method,
   1604 <code>allowDeviceAccess()</code>. When a LicenseValidator is handling a response
   1605 from the licensing server, it calls <code>allowDeviceAccess()</code>, passing a
   1606 user ID string extracted from the response.</p>
   1607 
   1608 <p>If you do not want to support device limitation, <strong>no work is
   1609 required</strong> &mdash; the LicenseChecker class automatically uses a default
   1610 implementation called NullDeviceLimiter. As the name suggests, NullDeviceLimiter
   1611 is a "no-op" class whose <code>allowDeviceAccess()</code> method simply returns
   1612 a <code>LICENSED</code> response for all users and devices. </p>
   1613 
   1614 <div style="border-left:4px solid #FFCF00;margin:1em;padding: 0 0 0 .5em">
   1615 <p><strong>Caution:</strong> Per-device licensing is <em>not recommended for
   1616 most applications</em> because:</p>
   1617 <ul>
   1618 <li>It requires that you provide a backend server to manage a users and devices
   1619 mapping, and </li>
   1620 <li>It could inadvertently result in a user being denied access to an
   1621 application that they have legitimately purchased on another device.</li>
   1622 </ul>
   1623 </div>
   1624 
   1625 
   1626 <h2 id="test-env">Setting Up the Testing Environment</h2>
   1627 
   1628 <p>The Android Market publisher site provides configuration tools that let you
   1629 and others test licensing on your application before it is published. As you are
   1630 implementing licensing, you can make use of the publisher site tools to test
   1631 your application's Policy and handling of different licensing responses and
   1632 error conditions.</p>
   1633 
   1634 <p>The main components of the test environment for licensing include: </p>
   1635 
   1636 <ul>
   1637 <li>A "Test response" configuration in your publisher account that lets you
   1638 set the static licensing response returned, when the server processes a
   1639 license check for an application uploaded to the publisher account, from a user
   1640 signed in to the publisher account or a test account.</li>
   1641 <li>An optional set of test accounts that will receive the static test
   1642 response when they check the license of an application that you have uploaded
   1643 (regardless whether the application is published or not).</li>
   1644 <li>A runtime environment for the application that includes the Android Market
   1645 application or Google APIs Add-On, on which the user is signed in to the
   1646 publisher account or one of the test accounts.</li>
   1647 </ul>
   1648 
   1649 <p>Setting up the test environment properly involves:</p>
   1650 
   1651 <ol>
   1652 <li><a href="#test-response">Setting static test responses</a> that are returned by the licensing server.</li>
   1653 <li><a href="#test-acct-setup">Setting up test accounts</a> as needed.</li>
   1654 <li><a href="#acct-signin">Signing in</a> properly to an emulator or device, before initiating a license check test.</li>
   1655 </ol>
   1656 
   1657 <p>The sections below provide more information.</p>
   1658 
   1659 
   1660 <h3 id="test-response">Setting test responses for license checks</h3>
   1661 
   1662 <p>Android Market provides a configuration setting in your publisher account
   1663 that lets you override the normal processing of a license check and return a
   1664 specified static response code. The setting is for testing only and applies
   1665 <em>only</em> to license checks for applications that you have uploaded, made by
   1666 any user signed in to an emulator or device using the credentials of the
   1667 publisher account or a registered test account. For other users, the server
   1668 always processes license checks according to normal rules.  </p>
   1669 
   1670 <p>To set a test response for your account, sign in to your publisher account
   1671 and click "Edit Profile". In the Edit Profile page, locate the Test Response
   1672 menu in the Licensing panel, shown below. You can select from the full set of
   1673 valid server response codes to control the response or condition you want to
   1674 test in your application.</p>
   1675 
   1676 <p>In general, you should make sure to test your application's licensing
   1677 implementation with every response code available in the Test Response menu.
   1678 For a description of the codes, see <a href="#server-response-codes">Server
   1679 Response Codes</a> in the Appendix of this document.</p>
   1680 
   1681 <div style="margin-bottom:2em;" id="licensing_test_response">
   1682 
   1683 <img src="{@docRoot}images/licensing_test_response.png" style="text-align:left;margin-bottom:0;" />
   1684 <div style="margin:0 2em;padding:0"><strong>Figure 7.</strong> The Licensing
   1685 panel of your account's Edit Profile page, showing the Test Accounts field and the
   1686 Test Response menu.</div>
   1687 </div>
   1688 
   1689 <p>Note that the test response that you configure applies account-wide &mdash;
   1690 that is, it applies not to a single application, but to <em>all</em>
   1691 applications associated with the publisher account. If you are testing multiple
   1692 applications at once, changing the test response will affect all of those
   1693 applications on their next license check (if the user is signed into
   1694 the emulator or device using the publisher account or a test account).</p>
   1695 
   1696 <p>Before you can successfully receive a test response for a license check,
   1697 you must sign in to the device or emulator on which the application
   1698 is installed, and from which it is querying the server. Specifically, you must
   1699 sign using either your publisher account or one of the test accounts that you
   1700 have set up. For more information about test accounts, see the next section.</p>
   1701 
   1702 <p>See <a href="#server-response-codes">Server Response Codes</a> for a list of
   1703 test responses available and their meanings. </p>
   1704 
   1705 
   1706 <h3 id="test-acct-setup">Setting up test accounts</h3>
   1707 
   1708 <p>In some cases, you might want to let multiple teams of developers test
   1709 licensing on applications that will ultimately be published through your
   1710 publisher account, but without giving them access to your publisher account's
   1711 sign-in credentials. To meet that need, the Android Market publisher site lets
   1712 you set up one or more optional <em>test accounts</em> &mdash; accounts that are
   1713 authorized to query the licensing server and receive static test responses from
   1714 your publisher account.</p>
   1715 
   1716 <p>Test accounts are standard Google accounts that you register on your
   1717 publisher account, such that they will receive the test response for
   1718 applications that you have uploaded. Developers can then sign in to their
   1719 devices or emulators using the test account credentials and initiate license
   1720 checks from installed applications. When the licensing server receives a license
   1721 check from a user of a test account, it returns the static test response
   1722 configured for the publisher account.  </p>
   1723 
   1724 <p>Necessarily, there are limitations on the access and permissions given to
   1725 users signed in through test accounts, including:</p>
   1726 
   1727 <ul>
   1728 <li>Test account users can query the licensing server only for applications that
   1729 are already uploaded to the publisher account. </li>
   1730 <li>Test account users do not have permission to upload applications to your
   1731 publisher account.</li>
   1732 <li>Test account users do not have permission to set the publisher account's
   1733 static test response.</li>
   1734 </ul>
   1735 
   1736 <p>The table below summarizes the differences in capabilities, between the
   1737 publisher account, a test account, and any other account.</p>
   1738 
   1739 <p class="table-caption" id="acct-types-table"><strong>Table 1.</strong>
   1740 Differences in account types for testing licensing.</p>
   1741 
   1742 <table>
   1743 <tr>
   1744 <th>Account Type</th>
   1745 <th>Can check license before upload?</th>
   1746 <th>Can receive test response?</th>
   1747 <th>Can set test response?</th>
   1748 </tr>
   1749 
   1750 <tr>
   1751 <td>Publisher account</td>
   1752 <td>Yes</td>
   1753 <td>Yes</td>
   1754 <td>Yes</td>
   1755 </tr>
   1756 
   1757 <tr>
   1758 <td>Test account</td>
   1759 <td>No</td>
   1760 <td>Yes</td>
   1761 <td>No</td>
   1762 </tr>
   1763 
   1764 <tr>
   1765 <td>Other</td>
   1766 <td>No</td>
   1767 <td>No</td>
   1768 <td>No</td>
   1769 </tr>
   1770 </table>
   1771 
   1772 <h4 id="reg-test-acct">Registering test accounts on the publisher account</h4>
   1773 
   1774 <p>To get started, you need to register each test account in your publisher
   1775 account. As shown in <a href="#licensing_test_response">Figure 7</a>, above, you
   1776 register test accounts in the Licensing panel of your publisher account's Edit
   1777 Profile page. Simply enter the accounts as a comma-delimited list and click
   1778 <strong>Save</strong> to save your profile changes.</p>
   1779 
   1780 <p>You can use any Google account as a test account. If you want to own and
   1781 control the test accounts, you can create the accounts yourself and distribute
   1782 the credentials to your developers or testers.</p>
   1783 
   1784 <h4 id="test-app-upload">Handling application upload and distribution for test
   1785 account users</h4>
   1786 
   1787 <p>As mentioned above, users of test accounts can only receive static test
   1788 responses for applications that are uploaded to the publisher account. Since
   1789 those users do not have permission to upload applications, as the publisher you
   1790 will need to work with those users to collect apps for upload and distribute
   1791 uploaded apps for testing. You can handle collection and distribution in any way
   1792 that is convenient. </p>
   1793 
   1794 <p>Once an application is uploaded and becomes known to the licensing server,
   1795 developers and testers can continue modify the application in their local
   1796 development environment, without having to upload new versions. You only need to
   1797 upload a new version if the local application increments the
   1798 <code>versionCode</code> attribute in the manifest file. </p>
   1799 
   1800 <h4 id="test-key">Distributing your public key to test account users</h4>
   1801 
   1802 <p>The licensing server handles static test responses in the normal way,
   1803 including signing the license response data, adding extras parameters, and so
   1804 on. To support developers who are implementing licensing using test accounts,
   1805 rather than the publisher account, you will need to distribute
   1806 your public key to them. Developers without access to the publisher site do not
   1807 have access to your public key, and without the key they won't be able to
   1808 verify license responses. </p>
   1809 
   1810 <p>Note that if you decide to generate a new licensing key pair for your account
   1811 for some reason, you need to notify all users of test accounts. For
   1812 testers, you can embed the new key in the application package and distribute it
   1813 to users. For developers, you will need to distribute the new key to them
   1814 directly. </p>
   1815 
   1816 
   1817 <h3 id="acct-signin">Signing in to an authorized account in the runtime
   1818 environment</h3>
   1819 
   1820 <p>The licensing service is designed to determine whether a given user is
   1821 licensed to use a given application &mdash; during a license check, the Android
   1822 Market application gathers the user ID from the primary account on the system
   1823 and sends it to the server, together with the package name of the application
   1824 and other information. However, if there is no user information available, the
   1825 license check cannot succeed, so the Android Market application terminates the
   1826 request and returns an error to the application. </p>
   1827 
   1828 <p>During testing, to ensure that your application can successfully query the
   1829 licensing server, you must make sure that you sign in to an account <em>on the
   1830 device or emulator</em> using:</p>
   1831 
   1832 <ul>
   1833 <li>The credentials of a publisher account, or</li>
   1834 <li>The credentials of a test account that is registered with a publisher
   1835 account</li>
   1836 </ul>
   1837 
   1838 
   1839 <div class="sidebox-wrapper">
   1840 <div class="sidebox">
   1841 <h2>Signing in to a Google account on an emulator</h2>
   1842 
   1843 <p>If you are testing licensing on an emulator, you need to sign in to a Google
   1844 account on the emulator. If you do not see an option to create a new Google
   1845 account, the problem might be that your AVD is running a standard Android system
   1846 image, rather than the Google APIs Add-On, API 8 (release 2) or higher. </p>
   1847 
   1848 <p style="margin-top:.5em;">For more information, see <a
   1849 href="#runtime-setup">Setting up the runtime environment</a>, above.</p>
   1850 
   1851 </div>
   1852 </div>
   1853 
   1854 <p>Signing in using a publisher account offers the advantage of letting your
   1855 applications receive static test responses even before the applications are
   1856 uploaded to the publisher site.</p>
   1857 
   1858 <p>If you are part of a larger organization or are working with external groups
   1859 on applications that will be published through your site, you will more likely
   1860 want to distribute test accounts instead, then use those to sign in during
   1861 testing. </p>
   1862 
   1863 <p>To sign in on a device or emulator, follow the steps below. The preferred
   1864 approach is to sign in as the primary account &mdash; however, if there are
   1865 other accounts already in use on the device or emulator, you can create an
   1866 additional account and sign in to it using the publisher or test account
   1867 credentials.  </p>
   1868 
   1869 <ol>
   1870 <li>Open Settings &gt; Accounts &amp; sync</li>
   1871 <li>Select <strong>Add Account</strong> and choose to add a "Google" account.
   1872 </li>
   1873 <li>Select <strong>Next</strong> and then <strong>Sign in</strong>.</li>
   1874 <li>Enter the username and password of either the publisher account or a test
   1875 account that is registered in the publisher account.</li>
   1876 <li>Select <strong>Sign in</strong>. The system signs you in to the new
   1877 account.</li>
   1878 </ol>
   1879 
   1880 <p>Once you are signed in, you can begin testing licensing in your application
   1881 (if you have completed the LVL integration steps above). When your application
   1882 initiates a license check, it will receive a response containing the static test
   1883 response configured on the publisher account. </p>
   1884 
   1885 <p>Note that, if you are using an emulator, you will need to sign in to the
   1886 publisher account or test account each time you wipe data when restarting the
   1887 emulator.</p>
   1888 
   1889 <div style="margin:2em 1em 1em 1em;">
   1890 
   1891 <img src="{@docRoot}images/licensing_device_signin.png" style="text-align:left;" />
   1892 <div style="margin:.25em 1.25em;padding:0"><strong>Figure 8.</strong> Example of
   1893 setting up a Google account on a device or emulator.</div>
   1894 </div>
   1895 
   1896 <h2 id="app-obfuscation">Obfuscating Your Application</h2>
   1897 
   1898 <p>To ensure the security of your application, particularly for a paid
   1899 application that uses licensing and/or custom constraints and protections, it's
   1900 very important to obfuscate your application code. Properly obfuscating your
   1901 code makes it more difficult for a malicious user to decompile the application's
   1902 bytecode, modify it &mdash; such as by removing the license check &mdash;
   1903 and then recompile it.</p>
   1904 
   1905 <p>Several obfuscator programs are available for Android applications, including
   1906 <a href="http://proguard.sourceforge.net/">ProGuard</a>, which also offers
   1907 code-optimization features. The use of ProGuard or a similar program to obfuscate
   1908 your code is <em>strongly recommended</em> for all applications that use Android
   1909 Market Licensing. </p>
   1910 
   1911 <h2 id="app-publishing">Publishing a Licensed Application</h2>
   1912 
   1913 <p>When you are finished testing your license implementation, you are ready to
   1914 publish the application on Android Market. Follow the normal steps to <a
   1915 href="{@docRoot}guide/publishing/preparing.html">prepare</a>, <a
   1916 href="{@docRoot}guide/publishing/app-signing.html">sign</a>, and then <a
   1917 href="{@docRoot}guide/publishing/publishing.html">publish the application</a>.
   1918 </p>
   1919 
   1920 <h4>Removing Copy Protection</h4>
   1921 
   1922 <p>After uploading your licensed application, remember to remove copy protection
   1923 from the application, if it is currently used. To check and remove copy
   1924 protection, sign in to the publisher site and go the application's upload
   1925 details page. In the Publishing options section, make sure that the Copy
   1926 Protection radio button selection is "Off".</p>
   1927 
   1928 <h4>Considerations for Free Apps</h4>
   1929 
   1930 <p>Licensing is currently supported only for paid applications. If you already
   1931 published your application as free, you won't be able to upload an updated
   1932 version that includes licensing (that is, an application that uses the same
   1933 package name and that includes the <a href="#manifest-permission">licensing
   1934 permission</a>). Here are some points to keep in mind:</p>
   1935 
   1936 <ul>
   1937 <li>If you want to offer a free version of your application that provides a
   1938 reduced feature set (or that offers the full feature set for trial period), the
   1939 free version of your application must not include the licensing permission and
   1940 must use a different package name than the paid version of the app.</li>
   1941 <li>If you want to offer a paid version of your free application that uses
   1942 licensing, you can do so under a new package name.</li>
   1943 </ul>
   1944 
   1945 <h2 id="support">Where to Get Support</h2>
   1946 
   1947 <p>If you have questions or encounter problems while implementing or deploying
   1948 publishing in your applications, please use the support resources listed in the
   1949 table below. By directing your queries to the correct forum, you can get the
   1950 support you need more quickly. </p>
   1951 
   1952 <p class="table-caption"><strong>Table 2.</strong> Developer support resources
   1953 for Android Market Licensing Service.</p>
   1954 
   1955 <table>
   1956 
   1957 <tr>
   1958 <th>Support Type</th>
   1959 <th>Resource</th>
   1960 <th>Range of Topics</th>
   1961 </tr>
   1962 <tr>
   1963 <td rowspan="2">Development and testing issues</td>
   1964 <td>Google Groups: <a
   1965 href="http://groups.google.com/group/android-developers">android-developers</a>
   1966 </td>
   1967 <td rowspan="2">LVL download and integration, library projects, Policy
   1968 questions, user experience ideas, handling of responses, Obfuscator, IPC, test
   1969 environment setup</td>
   1970 </tr>
   1971 <tr>
   1972 <td>Stack Overflow: <a
   1973 href="http://stackoverflow.com/questions/tagged/android">http://stackoverflow.com/questions/tagged/android</a></td>
   1974 </tr>
   1975 <tr>
   1976 <td rowspan="2">Accounts, publishing, and deployment issues</td>
   1977 <td><a href="http://www.google.com/support/forum/p/Android+Market">Android
   1978 Market Help Forum</a></td>
   1979 <td rowspan="2">Publisher accounts, licensing key pair, test accounts, server
   1980 responses, test responses, application deployment and results</td>
   1981 </tr>
   1982 <tr>
   1983 <td><a
   1984 href="http://market.android.com/support/bin/answer.py?answer=186113">Market
   1985 Licensing Support FAQ</a></td>
   1986 </tr>
   1987 <tr>
   1988 <td>LVL issue tracker</td>
   1989 <td><a href="http://code.google.com/p/marketlicensing/issues/">Marketlicensing
   1990 project issue tracker</a></td>
   1991 <td>Bug and issue reports related specifically to the LVL source code classes
   1992 and interface implementations</td>
   1993 </tr>
   1994 
   1995 </table>
   1996 
   1997 <p>For general information about how to post to the groups listed above, see <a
   1998 href="{@docRoot}resources/community-groups.html">Developer Forums</a> document
   1999 in the Resources tab.</p>
   2000 
   2001 <h2 id="lvl-summary">Summary of LVL Classes and Interfaces</h2>
   2002 
   2003 <p>The table below lists all of the source files in the License Verification
   2004 Library (LVL) available through the Android SDK. All of the files are part of
   2005 the <code>com.android.vending.licensing</code> package.</p>
   2006 
   2007 <p class="table-caption"><strong>Table A-1.</strong> Summary of LVL library
   2008 classes and interfaces.</p>
   2009 
   2010 <div style="width:99%">
   2011 <table width="100%">
   2012 
   2013 <tr>
   2014 <th width="15%">Category</th>
   2015 <th width="20%">Name</th>
   2016 <th width="100%">Description</th>
   2017 </tr>
   2018 
   2019 <tr>
   2020 <td rowspan="2">License check and result</td>
   2021 <td>LicenseChecker</td>
   2022 <td>Class that you instantiate (or subclass) to initiate a license check.</td>
   2023 </tr>
   2024 <tr>
   2025 <td><em>LicenseCheckerCallback</em></td>
   2026 <td>Interface that you implement to handle result of the license check.</td>
   2027 </tr>
   2028 
   2029 <tr>
   2030 <td rowspan="3" width="15%">Policy</td>
   2031 <td width="20%"><em>Policy</em></td>
   2032 <td width="100%">Interface that you implement to determine whether to allow
   2033 access to the application, based on the license response. </td>
   2034 </tr>
   2035 <tr>
   2036 <td>ServerManagedPolicy</td>
   2037 <td width="100%">Default Policy implementation. Uses settings provided by the
   2038 licensing server to manage local storage of license data, license validity,
   2039 retry.</td>
   2040 </tr>
   2041 <tr>
   2042 <td>StrictPolicy</td>
   2043 <td>Alternative Policy implementation. Enforces licensing based on a direct
   2044 license response from the server only. No caching or request retry.</td>
   2045 </tr>
   2046 
   2047 <tr>
   2048 <td rowspan="2" width="15%">Data obfuscation <br><em>(optional)</em></td>
   2049 <td width="20%"><em>Obfuscator</em></td>
   2050 <td width="100%">Interface that you implement if you are using a Policy (such as
   2051 ServerManagedPolicy) that caches license response data in a persistent store.
   2052 Applies an obfuscation algorithm to encode and decode data being written or
   2053 read.</td>
   2054 </tr>
   2055 <tr>
   2056 <td>AESObfuscator</td>
   2057 <td>Default Obfuscator implementation that uses AES encryption/decryption
   2058 algorithm to obfuscate/unobfuscate data.</td>
   2059 </tr>
   2060 
   2061 <tr>
   2062 <td rowspan="2" width="15%">Device limitation<br><em>(optional)</em></td>
   2063 <td width="20%"><em>DeviceLimiter</em></td>
   2064 <td width="100%">Interface that you implement if you want to restrict use of an
   2065 application to a specific device. Called from LicenseValidator. Implementing
   2066 DeviceLimiter is not recommended for most applications because it requires a
   2067 backend server and may cause the user to lose access to licensed applications,
   2068 unless designed with care.</td>
   2069 </tr>
   2070 <tr>
   2071 <td>NullDeviceLimiter</td>
   2072 <td>Default DeviceLimiter implementation that is a no-op (allows access to all
   2073 devices).</td>
   2074 </tr>
   2075 
   2076 <tr>
   2077 <td rowspan="6" width="15%">Library core, no integration needed</td>
   2078 <td width="20%">ResponseData</td>
   2079 <td width="100%">Class that holds the fields of a license response.</td>
   2080 </tr>
   2081 <tr>
   2082 <td>LicenseValidator</td>
   2083 <td>Class that decrypts and verifies a response received from the licensing
   2084 server.</td>
   2085 </tr>
   2086 <tr>
   2087 <td>ValidationException</td>
   2088 <td>Class that indicates errors that occur when validating the integrity of data
   2089 managed by an Obfuscator.</td>
   2090 </tr>
   2091 <tr>
   2092 <td>PreferenceObfuscator</td>
   2093 <td>Utility class that writes/reads obfuscated data to the system's
   2094 {@link android.content.SharedPreferences} store.</td>
   2095 </tr>
   2096 <tr>
   2097 <td><em>ILicensingService</em></td>
   2098 <td>One-way IPC interface over which a license check request is passed to the
   2099 Android Market client.</td>
   2100 </tr>
   2101 <tr>
   2102 <td><em>ILicenseResultListener</em></td>
   2103 <td>One-way IPC callback implementation over which the application receives an
   2104 asynchronous response from the licensing server.</td>
   2105 </tr>
   2106 
   2107 </table>
   2108 </div>
   2109 
   2110 
   2111 <h2 id="server-response-codes">Server Response Codes</h2>
   2112 
   2113 <p>The table below lists all of the license response codes supported by the
   2114 licensing server. In general, an application should handle all of these response
   2115 codes. By default, the LicenseValidator class in the LVL provides all of the
   2116 necessary handling of these response codes for you. </p>
   2117 
   2118 <p class="table-caption"><strong>Table A-2.</strong> Summary of response codes
   2119 returned by the Android Market server in a license response.</p>
   2120 
   2121 <table>
   2122 
   2123 <tr>
   2124 <th>Response Code</th>
   2125 <th>Description</th>
   2126 <th>Signed?</th>
   2127 <th>Extras</th>
   2128 <th>Comments</th>
   2129 </tr>
   2130 <tr>
   2131 <td>LICENSED</td>
   2132 <td>The application is licensed to the user. The user has purchased the
   2133 application or the application is free.</td>
   2134 <td>Yes</td>
   2135 <td><code>VT</code>,&nbsp;<code>GT</code>, <code>GR</code></td>
   2136 <td><em>Allow access according to Policy constraints.</em></td>
   2137 </tr>
   2138 <tr>
   2139 <td>LICENSED_OLD_KEY</td>
   2140 <td>The application is licensed to the user, but there is an updated application
   2141 version available that is signed with a different key. </td>
   2142 <td>Yes </td>
   2143 <td><code>VT</code>, <code>GT</code>, <code>GR</code>, <code>UT</code></td>
   2144 <td><em>Optionally allow access according to Policy constraints.</em>
   2145 <p style="margin-top:.5em;">Can indicate that the key pair used by the installed
   2146 application version is invalid or compromised. The application can allow access
   2147 if needed or inform the user that an upgrade is available and limit further use
   2148 until upgrade.</p>
   2149 </td>
   2150 </tr>
   2151 <tr>
   2152 <td>NOT_LICENSED</td>
   2153 <td>The application is not licensed to the user.</td>
   2154 <td>No</td>
   2155 <td></td>
   2156 <td><em>Do not allow access.</em></td>
   2157 </tr>
   2158 <tr>
   2159 <td>ERROR_CONTACTING_SERVER</td>
   2160 <td>Local error &mdash; the Android Market application was not able to reach the
   2161 licensing server, possibly because of network availability problems. </td>
   2162 <td>No</td>
   2163 <td></td>
   2164 <td><em>Retry the license check according to Policy retry limits.</em></td>
   2165 </tr>
   2166 <tr>
   2167 <td>ERROR_SERVER_FAILURE</td>
   2168 <td>Server error &mdash; the server could not load the publisher account's key
   2169 pair for licensing.</td>
   2170 <td>No</td>
   2171 <td></td>
   2172 <td><em>Retry the license check according to Policy retry limits.</em>
   2173 </td>
   2174 </tr>
   2175 <tr>
   2176 <td>ERROR_INVALID_PACKAGE_NAME</td>
   2177 <td>Local error &mdash; the application requested a license check for a package
   2178 that is not installed on the device. </td>
   2179 <td>No </td>
   2180 <td></td>
   2181 <td><em>Do not retry the license check.</em>
   2182 <p style="margin-top:.5em;">Typically caused by a development error.</p>
   2183 </td>
   2184 </tr>
   2185 <tr>
   2186 <td>ERROR_NON_MATCHING_UID</td>
   2187 <td>Local error &mdash; the application requested a license check for a package
   2188 whose UID (package, user ID pair) does not match that of the requesting
   2189 application. </td>
   2190 <td>No </td>
   2191 <td></td>
   2192 <td><em>Do not retry the license check.</em>
   2193 <p style="margin-top:.5em;">Typically caused by a development error.</p>
   2194 </td>
   2195 </tr>
   2196 <tr>
   2197 <td>ERROR_NOT_MARKET_MANAGED</td>
   2198 <td>Server error &mdash; the application (package name) was not recognized by
   2199 Android Market. </td>
   2200 <td>No</td>
   2201 <td></td>
   2202 <td><em>Do not retry the license check.</em>
   2203 <p style="margin-top:.5em;">Can indicate that the application was not published
   2204 through Android Market or that there is an development error in the licensing
   2205 implementation.</p>
   2206 </td>
   2207 </tr>
   2208 
   2209 </table>
   2210 
   2211 
   2212 <h2 id="extras">Server Response Extras</h2>
   2213 
   2214 <p>The licensing server includes several settings in certain types of license
   2215 responses, to assist the application and its Policy in managing access to the
   2216 application across the 24-hour refund period and other conditions. Specifically,
   2217 the server provides recommended values for the application's license validity
   2218 period, retry grace period, maximum allowable retry count, and other settings.
   2219 The server appends the settings as key-value pairs in the license response
   2220 "extras" field. </p>
   2221 
   2222 <p>Any Policy implementation can extract the extras settings from the license
   2223 response and use them as needed. The LVL default Policy implementation, <a
   2224 href="#ServerManagedPolicy">ServerManagedPolicy</a>, serves as a working
   2225 implementation and an illustration of how to obtain, store, and use the
   2226 settings. </p>
   2227 
   2228 <p class="table-caption"><strong>Table A-3.</strong> Summary of
   2229 license-management settings supplied by the Android Market server in a license
   2230 response.</p>
   2231 
   2232 <table>
   2233 <tr>
   2234 <th>Extra</th><th>Description</th>
   2235 </tr>
   2236 
   2237 <tr>
   2238   <td>VT</td>
   2239   <td>License validity timestamp. Specifies the date/time at which the current
   2240 (cached) license response expires and must be rechecked on the licensing server.
   2241  </td>
   2242 </tr>
   2243 <tr>
   2244   <td>GT</td>
   2245   <td>Grace period timestamp. Specifies the end of the period during which a
   2246 Policy may allow access to the application, even though the response status is
   2247 RETRY. <p>The value is managed by the server, however a typical value would be 5
   2248 or more days.</p></td>
   2249 </tr>
   2250 <tr>
   2251   <td>GR</td>
   2252   <td>Maximum retries count. Specifies how many consecutive RETRY license checks
   2253 the Policy should allow, before denying the user access to the application.
   2254 <p>The value is managed by the server, however a typical value would be "10" or
   2255 higher.</p></td>
   2256 </tr>
   2257 <tr>
   2258   <td>UT</td>
   2259   <td>Update timestamp. Specifies the day/time when the most recent update to
   2260 this application was uploaded and published. <p>The server returns this extra
   2261 only for LICENSED_OLD_KEYS responses, to allow the Policy to determine how much
   2262 time has elapsed since an update was published with new licensing keys before
   2263 denying the user access to the application. </p></td>
   2264 </tr>
   2265 
   2266 </table>
   2267 
   2268 <p>The sections below provide more information about the server-provided
   2269 settings and how to use them. </p>
   2270 
   2271 <h4>License validity period</h4>
   2272 
   2273 <p>The Android Market licensing server sets a license validity period for all
   2274 downloaded applications. The period expresses the interval of time over which an
   2275 application's license status should be considered as unchanging and cacheable by
   2276 a licensing Policy in the application. The licensing server includes the
   2277 validity period in its response to all license checks, appending an
   2278 end-of-validity timestamp to the response as an extra under the key "VT". A
   2279 Policy can extract the VT key value and use it to conditionally allow access to
   2280 the application without rechecking the license, until the validity period
   2281 expires. </p>
   2282 
   2283 <p>The license validity signals to a licensing Policy when it must recheck the
   2284 licensing status with the licensing server. It is <em>not</em> intended to imply
   2285 whether an application is actually licensed for use. That is, when an
   2286 application's license validity period expires, this does not mean that the
   2287 application is no longer licensed for use &mdash; rather, it indicates only that
   2288 the Policy must recheck the licensing status with the server. It follows that,
   2289 as long as the license validity period is not expired, it is acceptable for the
   2290 Policy to cache the initial license status locally and return the cached license
   2291 status instead of sending a new license check to the server.</p>
   2292 
   2293 <p>The licensing server manages the validity period as a means of helping the
   2294 application properly enforce licensing across the refund period offered by
   2295 Android Market for paid applications. It sets the validity period based on
   2296 whether the application was purchased and, if so, how long ago. Specifically,
   2297 the server sets a validity period as follows:</p>
   2298 
   2299 <ul>
   2300 <li>For a paid application, the server sets the initial license validity period
   2301 so that the license response remains valid for as long as the application is
   2302 refundable. A licensing Policy in the application may cache the
   2303 result of the initial license check and does not need to recheck the license
   2304 until the validity period has expired.</li>
   2305 <li>When an application is no longer refundable, the server
   2306 sets a longer validity period &mdash; typically a number of days. </li>
   2307 <li>For a free application, the server sets the validity period to a very high
   2308 value (<code>long.MAX_VALUE</code>). This ensures that, provided the Policy has
   2309 cached the validity timestamp locally, it will not need to recheck the
   2310 license status of the application in the future.</li>
   2311 </ul>
   2312 
   2313 <p>The ServerManagedPolicy implementation uses the extracted timestamp
   2314 (<code>mValidityTimestamp</code>) as a primary condition for determining whether
   2315 to recheck the license status with the server before allowing the user access to
   2316 the application. </p>
   2317 
   2318 <h4>Retry period and maximum retry count</h4>
   2319 
   2320 <p>In some cases, system or network conditions can prevent an application's
   2321 license check from reaching the licensing server, or prevent the server's
   2322 response from reaching the Android Market client application. For example, the
   2323 user might launch an application when there is no cell network or data
   2324 connection available &mdash; such as when on an airplane &mdash; or when the
   2325 network connection is unstable or the cell signal is weak. </p>
   2326 
   2327 <p>When network problems prevent or interrupt a license check, the Android
   2328 Market client notifies the application by returning a "RETRY" response code to
   2329 the Policy's <code>processServerResponse()</code> method. In the case of system
   2330 problems, such as when the application is unable to bind with Android Market's
   2331 ILicensingService implementation, the LicenseChecker library itself calls the
   2332 Policy <code>processServerResonse()</code> method with a "RETRY" response code.
   2333 </p>
   2334 
   2335 <p>In general, the RETRY response code is a signal to the application that an
   2336 error has occurred that has prevented a license check from completing. 
   2337 
   2338 <p>The Android Market server helps an application to manage licensing under
   2339 error conditions by setting a retry "grace period" and a recommended maximum
   2340 retries count. The server includes these values in all license check responses,
   2341 appending them as extras under the keys "GT" and "GR". </p>
   2342 
   2343 <p>The application Policy can extract the GT and GR extras and use them to
   2344 conditionally allow access to the application, as follows:</p>
   2345 
   2346 <ul>
   2347 <li>For a license check that results in a RETRY response, the Policy should
   2348 cache the RETRY response code and increment a count of RETRY responses.</li>
   2349 <li>The Policy should allow the user to access the application, provided that
   2350 either the retry grace period is still active or the maximum retries count has
   2351 not been reached.</li>
   2352 </ul>
   2353 
   2354 <p>The ServerManagedPolicy uses the server-supplied GT and GR values as
   2355 described above. The example below shows the conditional handling of the retry
   2356 responses in the <code>allow()</code> method. The count of RETRY responses is
   2357 maintained in the <code>processServerResponse()</code> method, not shown. </p>
   2358 
   2359 
   2360 <pre>    public boolean allowAccess() {
   2361         long ts = System.currentTimeMillis();
   2362         if (mLastResponse == LicenseResponse.LICENSED) {
   2363             // Check if the LICENSED response occurred within the validity timeout.
   2364             if (ts &lt;= mValidityTimestamp) {
   2365                 // Cached LICENSED response is still valid.
   2366                 return true;
   2367             }
   2368         } else if (mLastResponse == LicenseResponse.RETRY &amp;&amp;
   2369                    ts &lt; mLastResponseTime + MILLIS_PER_MINUTE) {
   2370             // Only allow access if we are within the retry period or we haven't used up our
   2371             // max retries.
   2372             return (ts &lt;= mRetryUntil || mRetryCount &lt;= mMaxRetries);
   2373         }
   2374         return false;
   2375     }</pre>
   2376 
   2377