OSDN Git Service

original
[gb-231r1-is01/Gingerbread_2.3.3_r1_IS01.git] / frameworks / base / docs / html / guide / publishing / licensing.jd
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     &lt;!-- Devices &gt;= 3 have version of Android Market that supports licensing. --&gt;
788     &lt;uses-sdk android:minSdkVersion="3" /&gt;
789     &lt;!-- Required permission to check licensing. --&gt;
790     &lt;uses-permission android:name="com.android.vending.CHECK_LICENSE" /&gt;
791     ...
792 &lt;/manifest&gt;
793 </pre>
794
795 <p class="note"><strong>Note:</strong> Currently, you cannot declare the
796 <code>CHECK_LICENSE</code> permission in the LVL library project's manifest,
797 because the SDK Tools will not merge it into the manifests of dependent
798 applications. Instead, you must declare the permission in each dependent
799 application's manifest. </p>
800
801
802 <h3 id="impl-Policy">Implementing a Policy</h3>
803
804 <div class="sidebox-wrapper">
805 <div class="sidebox">
806 <h2>ServerManagedPolicy</h2>
807
808 <p>The LVL includes a complete Policy implementation called ServerManagedPolicy
809 that makes use of license-management settings provided by the Android Market
810 server. </p>
811
812 <p style="margin-top:.5em;">Use of ServerManagedPolicy as the basis for your
813 Policy is strongly recommended. For more information, see <a
814 href="#ServerManagedPolicy">ServerManagedPolicy</a> section, below.</p>
815
816 </div>
817 </div>
818
819 <p>Android Market licensing service does not itself determine whether a
820 given user with a given license should be granted access to your application.
821 Rather, that responsibility is left to a Policy implementation that you provide
822 in your application.</p>
823
824 <p>Policy is an interface declared by the LVL that is designed to hold your
825 application's logic for allowing or disallowing user access, based on the result
826 of a license check. To use the LVL, your application <em>must</em> provide an
827 implementation of Policy. </p>
828
829 <p>The Policy interface declares two methods, <code>allowAccess()</code> and
830 <code>processServerResponse()</code>, which are called by a LicenseChecker
831 instance when processing a response from the license server. It also declares an
832 enum called <code>LicenseResponse</code>, which specifies the license response
833 value passed in calls to <code>processServerResponse()</code>. </p>
834
835 <ul>
836 <li><code>processServerResponse()</code> lets you preprocess the raw response
837 data received from the licensing server, prior to determining whether to grant
838 access.
839
840 <p>A typical implementation would extract some or all fields from the license
841 response and store the data locally to a persistent store, such as through
842 {@link android.content.SharedPreferences} storage, to ensure that the data is
843 accessible across application invocations and device power cycles. For example,
844 a Policy would maintain the timestamp of last successful license check, the
845 retry count, the license validity period, and similar information in a
846 persistent store, rather than resetting the values each time the application is
847 launched.</p>
848
849 <p>When storing response data locally, the Policy must ensure that the data is
850 obfuscated (see <a href="#impl-Obfuscator">Implementing an Obfuscator</a>,
851 below).</p></li>
852
853 <li><code>allowAccess()</code> determines whether to grant the user access to
854 your application, based on any available license response data (from the
855 licensing server or from cache) or other application-specific information.  For
856 example, your implementation of <code>allowAccess()</code> could take into
857 account additional criteria, such as usage or other data retrieved from a
858 backend server. In all cases, an implementation of <code>allowAccess()</code>
859 should only return <code>true</code> if the user is licensed to use the
860 application, as determined by the licensing server, or if there is a transient
861 network or system problem that prevents the license check from completing. In
862 such cases, your implementation can maintain a count of retry responses and
863 provisionally allow access until the next license check is complete.</li>
864
865 </ul>
866
867 <p>To simplify the process of adding licensing to your application and to
868 provide an illustration of how a Policy should be designed, the LVL includes
869 two full Policy implementations that you can use without modification or
870 adapt to your needs:</p>
871
872 <ul>
873 <li><a href="#ServerManagedPolicy">ServerManagedPolicy</a>, a flexible Policy
874 that uses server-provided settings and cached responses to manage access across
875 varied network conditions, and</li>
876 <li><a href="#StrictPolicy">StrictPolicy</a>, which does not cache any response
877 data and allows access <em>only</em> if the server returns a licensed
878 response.</li>
879 </ul>
880
881 <p>For most applications, the use of ServerManagedPolicy is highly
882 recommended. ServerManagedPolicy is the LVL default and is integrated with
883 the LVL sample application.</p>
884
885
886 <h4 id="custom-policies">Guidelines for custom policies</h4>
887
888 <p>In your licensing implementation, you can use one of the complete policies
889 provided in the LVL (ServerManagedPolicy or StrictPolicy) or you can create a
890 custom policy. For any type of custom policy, there are several important design
891 points to understand and account for in your implementation.</p>
892
893 <p>The licensing server applies general request limits to guard against overuse
894 of resources that could result in denial of service. When an application exceeds
895 the request limit, the licensing server returns a 503 response, which gets
896 passed through to your application as a general server error. This means that no
897 license response will be available to the user until the limit is reset, which
898 can affect the user for an indefinite period.</p>
899
900 <p>If you are designing a custom policy, we recommend that the Policy:
901 <ol>
902 <!-- <li>Limits the number of points at which your app calls for a license check
903 to the minimum. </li> -->
904 <li>Caches (and properly obfuscates) the most recent successful license response
905 in local persistent storage.</li>
906 <li>Returns the cached response for all license checks, for as long as the
907 cached response is valid, rather than making a request to the licensing server.
908 Setting the response validity according to the server-provided <code>VT</code>
909 extra is highly recommended. See <a href="#extras">Server Response Extras</a>
910 for more information.</li>
911 <li>Uses an exponential backoff period, if retrying any requests the result in
912 errors. Note that the Android Market client automatically retries failed
913 requests, so in most cases there is no need for your Policy to retry them.</li>
914 <li>Provides for a "grace period" that allows the user to access your
915 application for a limited time or number of uses, while a license check is being
916 retried. The grace period benefits the user by allowing access until the next
917 license check can be completed successfully and it benefits you by placing a
918 hard limit on access to your application when there is no valid license response
919 available.</li>
920 </ol>
921
922 <p>Designing your Policy according to the guidelines listed above is critical,
923 because it ensures the best possible experience for users while giving you
924 effective control over your application even in error conditions. </p>
925
926 <p>Note that any Policy can use settings provided by the licensing server to
927 help manage validity and caching, retry grace period, and more. Extracting the
928 server-provided settings is straightforward and making use of them is highly
929 recommended. See the ServerManagedPolicy implementation for an example of how to
930 extract and use the extras. For a list of server settings and information about
931 how to use them, see  <a href="#extras">Server Response Extras</a> in the
932 Appendix of this document.</p>
933
934 <h4 id="ServerManagedPolicy">ServerManagedPolicy</h4>
935
936 <div class="sidebox-wrapper">
937 <div class="sidebox">
938 <h2>Server Response Extras</h2>
939
940 <p>For certain types of licensing responses, the licensing server appends extra
941 settings to the responses, to help the application manage licensing effectively.
942 </p>
943
944 <p style="margin-top:.5em;">See <a href="#extras">Server Response Extras</a> for
945 a list of settings and <code>ServerManagedPolicy.java</code> for information
946 about how a Policy can use the extras.</p>
947
948 </div>
949 </div>
950
951 <p>The LVL includes a full and recommended implementation of the Policy
952 interface called ServerManagedPolicy. The implementation is integrated with the
953 LVL classes and serves as the default Policy in the library. </p>
954
955 <p>ServerManagedPolicy provides all of the handling for license and retry
956 responses. It caches all of the response data locally in a
957 {@link android.content.SharedPreferences} file, obfuscating it with the
958 application's Obfuscator implementation. This ensures that the license response
959 data is secure and persists across device power cycles. ServerManagedPolicy
960 provides concrete implementations of the interface methods
961 <code>processServerResponse()</code> and <code>allowAccess()</code> and also
962 includes a set of supporting methods and types for managing license
963 responses.</p>
964
965 <p>Importantly, a key feature of ServerMangedPolicy is its use of
966 server-provided settings as the basis for managing licensing across an
967 application's refund period and through varying network and error conditions.
968 When an application contacts the Android Market server for a license check, the
969 server appends several settings as key-value pairs in the extras field of certain
970 license response types. For example, the server provides recommended values for the
971 application's license validity period, retry grace period, and maximum allowable
972 retry count, among others. ServerManagedPolicy extracts the values from the
973 license response in its <code>processServerResponse()</code> method and checks
974 them in its <code>allowAccess()</code> method. For a list of the server-provided
975 settings used by ServerManagedPolicy, see <a href="#extras">Server Response
976 Extras</a> in the Appendix of this document.</p>
977
978 <p>For convenience, best performance, and the benefit of using license settings
979 from the Android Market server, <strong>using ServerManagedPolicy as your
980 licensing Policy is strongly recommended</strong>. </p>
981
982 <p>If you are concerned about the security of license response data that is
983 stored locally in SharedPreferences, you can use a stronger obfuscation
984 algorithm or design a stricter Policy that does not store license data. The LVL
985 includes an example of such a Policy &mdash; see <a
986 href="#StrictPolicy">StrictPolicy</a> for more information.</p>
987
988 <p>To use ServerManagedPolicy, simply import it to your Activity, create an
989 instance, and pass a reference to the instance when constructing your
990 LicenseChecker. See <a href="#lc-lcc">Instantiate LicenseChecker and
991 LicenseCheckerCallback</a> for more information. </p>
992
993 <h4 id="StrictPolicy">StrictPolicy</h4>
994
995 <p>The LVL includes an alternative full implementation of the Policy interface
996 called StrictPolicy. The StrictPolicy implementation provides a more restrictive
997 Policy than ServerManagedPolicy, in that it does not allow the user to access
998 the application unless a license response is received from the server at the
999 time of access that indicates that the user is licensed.</p>
1000
1001 <p>The principal feature of StrictPolicy is that it does not store <em>any</em>
1002 license response data locally, in a persistent store. Because no data is stored,
1003 retry requests are not tracked and cached responses can not be used to fulfill
1004 license checks. The Policy allows access only if:</p>
1005
1006 <ul>
1007 <li>The license response is received from the licensing server, and </li>
1008 <li>The license response indicates that the user is licensed to access the
1009 application. </li>
1010 </ul>
1011
1012 <p>Using StrictPolicy is appropriate if your primary concern is to ensure that,
1013 in all possible cases, no user will be allowed to access the application unless
1014 the user is confirmed to be licensed at the time of use. Additionally, the
1015 Policy offers slightly more security than ServerManagedPolicy &mdash; since
1016 there is no data cached locally, there is no way a malicious user could tamper
1017 with the cached data and obtain access to the application.</p>
1018
1019 <p>At the same time, this Policy presents a challenge for normal users, since it
1020 means that they won't be able to access the application when there is no network
1021 (cell or wi-fi) connection available. Another side-effect is that your
1022 application will send more license check requests to the server, since using a
1023 cached response is not possible.</p>
1024
1025 <p>Overall, this policy represents a tradeoff of some degree of user convenience
1026 for absolute security and control over access. Consider the tradeoff carefully
1027 before using this Policy.</p>
1028
1029 <p>To use StrictPolicy, simply import it to your Activity, create an instance,
1030 and pass a reference to it when constructing your LicenseChecker. See
1031 <a href="#lc-lcc">Instantiate LicenseChecker and LicenseCheckerCallback</a>
1032 for more information. </p>
1033
1034 <h3 id="impl-Obfuscator">Implementing an Obfuscator</h3>
1035
1036 <div class="sidebox-wrapper">
1037 <div class="sidebox">
1038 <h2>AESObfuscator</h2>
1039
1040 <p>The LVL includes a full Obfuscator implementation in the
1041 <code>AESObfuscator.java</code> file. The Obfuscator uses AES encryption to
1042 obfuscate/unobfuscate data. If you are using a Policy (such as
1043 ServerManagedPolicy) that caches license response data, using AESObfuscator as
1044 basis for your Obfuscator implementation is highly recommended. </p>
1045
1046 </div>
1047 </div>
1048
1049 <p>A typical Policy implementation needs to save the license response data for
1050 an application to a persistent store, so that it is accessible across
1051 application invocations and device power cycles.  For example, a Policy would
1052 maintain the timestamp of the last successful license check, the retry count,
1053 the license validity period, and similar information in a persistent store,
1054 rather than resetting the values each time the application is launched. The
1055 default Policy included in the LVL, ServerManagedPolicy, stores license response
1056 data in a {@link android.content.SharedPreferences} instance, to ensure that the
1057 data is persistent. </p>
1058
1059 <p>Because the Policy will use stored license response data to determine whether
1060 to allow or disallow access to the application, it <em>must</em> ensure that any
1061 stored data is secure and cannot be reused or manipulated by a root user on a
1062 device. Specifically, the Policy must always obfuscate the data before storing
1063 it, using a key that is unique for the application and device. Obfuscating using
1064 a key that is both application-specific and device-specific is critical, because
1065 it prevents the obfuscated data from being shared among applications and
1066 devices.</p>
1067
1068 <p>The LVL assists the application with storing its license response data in a
1069 secure, persistent manner. First, it provides an Obfuscator
1070 interface that lets your application supply the obfuscation algorithm of its
1071 choice for stored data. Building on that, the LVL provides the helper class
1072 PreferenceObfuscator, which handles most of the work of calling the
1073 application's Obfuscator class and reading and writing the obfuscated data in a
1074 SharedPreferences instance. </p>
1075
1076 <p>The LVL provides a full Obfuscator implementation called
1077 AESObfuscator that uses AES encryption to obfuscate data. You can
1078 use AESObfuscator in your application without modification or you
1079 can adapt it to your needs. For more information, see the next section.</p>
1080
1081
1082 <h4 id="AESObfuscator">AESObfuscator</h4>
1083
1084 <p>The LVL includes a full and recommended implementation of the Obfuscator
1085 interface called AESObfuscator. The implementation is integrated with the
1086 LVL sample application and serves as the default Obfuscator in the library. </p>
1087
1088 <p>AESObfuscator provides secure obfuscation of data by using AES to
1089 encrypt and decrypt the data as it is written to or read from storage.
1090 The Obfuscator seeds the encryption using three data fields provided
1091 by the application: </p>
1092
1093 <ol>
1094 <li>A salt &mdash; an array of random bytes to use for each (un)obfuscation. </li>
1095 <li>An application identifier string, typically the package name of the application.</li>
1096 <li>A device identifier string, derived from as many device-specific sources
1097 as possible, so as to make it as unique.</li>
1098 </ol>
1099
1100 <p>To use AESObfuscator, first import it to your Activity. Declare a private
1101 static final array to hold the salt bytes and initialize it to 20 randomly
1102 generated bytes.</p>
1103
1104 <pre>    ...
1105     // Generate 20 random bytes, and put them here.
1106     private static final byte[] SALT = new byte[] {
1107      -46, 65, 30, -128, -103, -57, 74, -64, 51, 88, -95,
1108      -45, 77, -117, -36, -113, -11, 32, -64, 89
1109      };
1110     ...
1111 </pre>
1112
1113 <p>Next, declare a variable to hold a device identifier and generate a value for
1114 it in any way needed. For example, the sample application included in the LVL
1115 queries the system settings for the
1116 <code>android.Settings.Secure.ANDROID_ID</code>, which is unique to each device.
1117 </p>
1118
1119 <p>Note that, depending on the APIs you use, your application might need to
1120 request additional permissions in order to acquire device-specific information.
1121 For example, to query the {@link android.telephony.TelephonyManager} to obtain
1122 the device IMEI or related data, the application will also need to request the
1123 <code>android.permission.READ_PHONE_STATE</code> permission in its manifest.</p>
1124
1125 <p>Before requesting new permissions for the <em>sole purpose</em> of acquiring
1126 device-specific information for use in your Obfuscator, consider
1127 how doing so might affect your application or its filtering on Android Market
1128 (since some permissions can cause the SDK build tools to add
1129 the associated <code>&lt;uses-feature&gt;</code>).</p>
1130
1131 <p>Finally, construct an instance of AESObfuscator, passing the salt,
1132 application identifier, and device identifier. You can construct the instance
1133 directly, while constructing your Policy and LicenseChecker. For example:</p>
1134
1135 <pre>    ...
1136     // Construct the LicenseChecker with a Policy.
1137     mChecker = new LicenseChecker(
1138         this, new ServerManagedPolicy(this,
1139             new AESObfuscator(SALT, getPackageName(), deviceId)),
1140         BASE64_PUBLIC_KEY  // Your public licensing key.
1141         );
1142     ...
1143 </pre>
1144
1145 <p>For a complete example, see MainActivity in the LVL sample application.</p>
1146
1147
1148 <h3 id="impl-lc">Checking the license from your application's main Activity</h3>
1149
1150 <p>Once you've implemented a Policy for managing access to your application, the
1151 next step is to add a license check to your application, which initiates a query
1152 to the licensing server if needed and manages access to the application based on
1153 the license response. All of the work of adding the license check and handling
1154 the response takes place in your main {@link android.app.Activity} source file.
1155 </p>
1156
1157 <p>To add the license check and handle the response, you must:</p>
1158
1159 <ol>
1160     <li><a href="#imports">Add imports</a></li>
1161     <li><a href="#lc-impl">Implement LicenseCheckerCallback</a> as a private inner class</li>
1162     <li><a href="#thread-handler">Create a Handler</a> for posting from LicenseCheckerCallback to the UI thread</li>
1163     <li><a href="#lc-lcc">Instantiate LicenseChecker</a> and LicenseCheckerCallback</li>
1164     <li><a href="#check-access">Call checkAccess()</a> to initiate the license check</li>
1165     <li><a href="#account-key">Embed your public key</a> for licensing</li>
1166     <li><a href="#handler-cleanup">Call your LicenseChecker's onDestroy() method</a> to close IPC connections.</li>
1167 </ol>
1168
1169 <p>The sections below describe these tasks. </p>
1170
1171 <h4 id="lc-overview">Overview of license check and response</h4>
1172
1173 <div class="sidebox-wrapper">
1174 <div class="sidebox">
1175 <h2>Example: MainActivity</h2>
1176
1177 <p>The sample application included with the LVL provides a full example of how
1178 to initiate a license check and handle the result, in the
1179 <code>MainActivity.java</code> file.</p>
1180
1181 </div>
1182 </div>
1183
1184 <p>In most cases, you should add the license check to your application's main
1185 {@link android.app.Activity}, in the <code>onCreate()</code> method. This
1186 ensures that when the user launches your application directly, the license check
1187 will be invoked immediately. In some cases, you can add license checks in other
1188 locations as well. For example, if your application includes multiple Activity
1189 components that other applications can start by {@link android.content.Intent},
1190 you could add license checks in those Activities.</p>
1191
1192 <p>A license check consists of two main actions: </p>
1193
1194 <ul>
1195 <li>A call to a method to initiate the license check &mdash; in the LVL, this is
1196 a call to the <code>checkAccess()</code> method of a LicenseChecker object that
1197 you construct.</li>
1198 <li>A callback that returns the result of the license check. In the LVL, this is
1199 a <code>LicenseCheckerCallback</code> interface that you implement. The
1200 interface declares two methods, <code>allow()</code> and
1201 <code>dontAllow()</code>, which are invoked by the library based on to the
1202 result of the license check. You implement those two methods with whatever logic
1203 you need, to allow or disallow the user access to your application. Note that
1204 these methods do not determine <em>whether</em> to allow access &mdash; that
1205 determination is the responsibility of your Policy implementation. Rather, these
1206 methods simply provide the application behaviors for <em>how</em> to allow and
1207 disallow access (and handle application errors).</li>
1208 </ul>
1209
1210 <div style="margin-bottom:2em;">
1211
1212 <img src="{@docRoot}images/licensing_flow.png" style="text-align:left;margin-bottom:0;margin-left:3em;" />
1213 <div style="margin:.5em 0 1.5em 2em;padding:0"><strong>Figure 6.</strong> Overview of a
1214 typical license check interaction.</div>
1215 </div>
1216
1217 <p>The diagram above illustrates how a typical license check takes place: </p>
1218
1219 <ol>
1220 <li>Code in the application's main Activity instantiates LicenseCheckerCallback
1221 and LicenseChecker objects. When constructing LicenseChecker, the code passes in
1222 {@link android.content.Context}, a Policy implementation to use, and the
1223 publisher account's public key for licensing as parameters. </li>
1224 <li>The code then calls the <code>checkAccess()</code> method on the
1225 LicenseChecker object. The method implementation calls the Policy to determine
1226 whether there is a valid license response cached locally, in
1227 {@link android.content.SharedPreferences}.
1228 <ul>
1229 <li>If so, the <code>checkAccess()</code> implementation calls
1230 <code>allow()</code>.</li>
1231 <li>Otherwise, the LicenseChecker initiates a license check request that is sent
1232 to the licensing server.</li>
1233 </ul>
1234 </li>
1235 <li>When a response is received, LicenseChecker creates a LicenseValidator that
1236 verifies the signed license data and extracts the fields of the response, then
1237 passes them to your Policy for further evaluation.
1238   <ul>
1239     <li>If the license is valid, the Policy caches the response in
1240 SharedPreferences and notifies the validator, which then calls the
1241 <code>allow()</code> method on the LicenseCheckerCallback object. </li>
1242     <li>If the license not valid, the Policy notifies the validator, which calls
1243 the <code>dontAllow()</code> method on LicenseCheckerCallback. </li>
1244   </ul>
1245 </li>
1246 <li>In case of a recoverable local or server error, such as when the network is
1247 not available to send the request, LicenseChecker passes a RETRY response to
1248 your Policy's <code>processServerResponse()</code> method. </li>
1249 <li>In case of a application error, such as when the application attempts to
1250 check the license of an invalid package name, LicenseChecker passes an error
1251 response to the LicenseCheckerCallback's  <code>applicationError()</code>
1252 method. </li>
1253 </ol>
1254
1255 <p>Note that, in addition to initiating the license check and handling the
1256 result, which are described in the sections below, your application also needs
1257 to provide a <a href="#impl-Policy">Policy implementation</a> and, if the Policy
1258 stores response data (such as ServerManagedPolicy), an <a
1259 href="#impl-Obfuscator">Obfuscator</a> implementation. </p>
1260
1261
1262 <h4 id="imports">Add imports</h4>
1263
1264 <p>First, open the class file of the application's main Activity and import
1265 LicenseChecker and LicenseCheckerCallback from the LVL package.</p>
1266
1267 <pre>    import com.android.vending.licensing.LicenseChecker;
1268     import com.android.vending.licensing.LicenseCheckerCallback;</pre>
1269
1270 <p>If you are using the default Policy implementation provided with the LVL,
1271 ServerManagedPolicy, import it also, together with the AESObfuscator. If you are
1272 using a custom Policy or Obfuscator, import those instead. </p>
1273
1274 <pre>    import com.android.vending.licensing.ServerManagedPolicy;
1275     import com.android.vending.licensing.AESObfuscator;</pre>
1276
1277 <h4 id="lc-impl">Implement LicenseCheckerCallback as a private inner class</h4>
1278
1279 <p>LicenseCheckerCallback is an interface provided by the LVL for handling
1280 result of a license check. To support licensing using the LVL, you must
1281 implement LicenseCheckerCallback and
1282 its methods to allow or disallow access to the application.</p>
1283
1284 <p>The result of a license check is always a call to one of the
1285 LicenseCheckerCallback methods, made based on the validation of the response
1286 payload, the server response code itself, and any additional processing provided
1287 by your Policy. Your application can implement the methods in any way needed. In
1288 general, it's best to keep the methods simple, limiting them to managing UI
1289 state and application access. If you want to add further processing of license
1290 responses, such as by contacting a backend server or applying custom constraints,
1291 you should consider incorporating that code into your Policy, rather than
1292 putting it in the LicenseCheckerCallback methods. </p>
1293
1294 <p>In most cases, you should declare your implementation of
1295 LicenseCheckerCallback as a private class inside your application's main
1296 Activity class. </p>
1297
1298 <p>Implement the <code>allow()</code> and <code>dontAllow()</code> methods as
1299 needed. To start with, you can use simple result-handling behaviors in the
1300 methods, such as displaying the license result in a dialog. This helps you get
1301 your application running sooner and can assist with debugging. Later, after you
1302 have determined the exact behaviors you want, you can add more complex handling.
1303 </p>
1304
1305 <p>Some suggestions for handling unlicensed responses in
1306 <code>dontAllow()</code> include: </p>
1307
1308 <ul>
1309 <li>Display a "Try again" dialog to the user, including a button to initiate a
1310 new license check. </li>
1311 <li>Display a "Purchase this application" dialog, including a button that
1312 deep-links the user to the application's details page on Market, from which the
1313 use can purchase the application. For more information on how to set up such
1314 links, see <a
1315 href="{@docRoot}guide/publishing/publishing.html#marketintent">Using Intents to
1316 Launch the Market Application on a Device</a>. </li>
1317 <li>Display a Toast notification that indicates that the features of the
1318 application are limited because it is not licensed. </li>
1319 </ul>
1320
1321 <p>The example below shows how the LVL sample application implements
1322 LicenseCheckerCallback, with methods that display the license check result in a
1323 dialog. </p>
1324
1325 <pre>    private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
1326         public void allow() {
1327             if (isFinishing()) {
1328                 // Don't update UI if Activity is finishing.
1329                 return;
1330             }
1331             // Should allow user access.
1332             displayResult(getString(R.string.allow));
1333         }
1334
1335         public void dontAllow() {
1336             if (isFinishing()) {
1337                 // Don't update UI if Activity is finishing.
1338                 return;
1339             }
1340             displayResult(getString(R.string.dont_allow));
1341             // Should not allow access. An app can handle as needed,
1342             // typically by informing the user that the app is not licensed
1343             // and then shutting down the app or limiting the user to a
1344             // restricted set of features.
1345             // In this example, we show a dialog that takes the user to Market.
1346             showDialog(0);
1347         }
1348     }
1349 </pre>
1350
1351 <p>Additionally, you should implement the <code>applicationError()</code>
1352 method, which the LVL calls to let your application handle errors that are not
1353 retryable. For a list of such errors, see <a
1354 href="#server-response-codes">Server Response Codes</a> in the Appendix of this
1355 document. You can implement the method in any way needed. In most cases, the
1356 method should log the error code and call <code>dontAllow()</code>.</p>
1357
1358 <h4 id="thread-handler">Create a Handler for posting from LicenseCheckerCallback
1359 to the UI thread</h4>
1360
1361 <p>During a license check, the LVL passes the request to the Android Market
1362 application, which handles communication with the licensing server. The LVL
1363 passes the request over asynchronous IPC (using {@link android.os.Binder}) so
1364 the actual processing and network communication do not take place on a thread
1365 managed by your application. Similarly, when the Android Market application
1366 receives the result, it invokes a  callback method over IPC, which in turn
1367 executes in an IPC thread pool in your application's process.</p>
1368
1369 <p>The LicenseChecker class manages your application's IPC communication with
1370 the Android Market application, including the call that sends the request and
1371 the callback that receives the response. LicenseChecker also tracks open license
1372 requests and manages their timeouts. </p>
1373
1374 <p>So that it can handle timeouts properly and also process incoming responses
1375 without affecting your application's UI thread, LicenseChecker spawns a
1376 background thread at instantiation. In the thread it does all processing of
1377 license check results, whether the result is a response received from the server
1378 or a timeout error. At the conclusion of processing, the LVL calls your
1379 LicenseCheckerCallback methods from the background thread. </p>
1380
1381 <p>To your application, this means that:</p>
1382
1383 <ol>
1384 <li>Your LicenseCheckerCallback methods will be invoked, in many cases, from a
1385 background thread.</li>
1386 <li>Those methods won't be able to update state or invoke any processing in the
1387 UI thread, unless you create a Handler in the UI thread and have your callback
1388 methods post to the Handler.</li>
1389 </ol>
1390
1391 <p>If you want your LicenseCheckerCallback methods to update the UI thread,
1392 instantiate a {@link android.os.Handler} in the main Activity's 
1393 {@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method,
1394 as shown below. In this example, the LVL sample application's
1395 LicenseCheckerCallback methods (see above) call <code>displayResult()</code> to
1396 update the UI thread through the Handler's
1397 {@link android.os.Handler#post(java.lang.Runnable) post()} method.</p>
1398
1399 <pre>private Handler mHandler;
1400
1401     &#64;Override
1402     public void onCreate(Bundle savedInstanceState) {
1403         ...
1404         mHandler = new Handler();
1405     }
1406 </pre>
1407
1408 <p>Then, in your LicenseCheckerCallback methods, you can use Handler methods to
1409 post Runnable or Message objects to the Handler. Here's how the sample
1410 application included in the LVL posts a Runnable to a Handler in the UI thread
1411 to display the license status.</p>
1412
1413 <pre>    private void displayResult(final String result) {
1414         mHandler.post(new Runnable() {
1415             public void run() {
1416                 mStatusText.setText(result);
1417                 setProgressBarIndeterminateVisibility(false);
1418                 mCheckLicenseButton.setEnabled(true);
1419             }
1420         });
1421     }
1422 </pre>
1423
1424 <h4 id="lc-lcc">Instantiate LicenseChecker and LicenseCheckerCallback</h4>
1425
1426 <p>In the main Activity's
1427 {@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method,
1428 create private instances of LicenseCheckerCallback and LicenseChecker. You must
1429 instantiate LicenseCheckerCallback first, because you need to pass a reference
1430 to that instance when you call the contructor for LicenseChecker. </p>
1431
1432 <p>When you instantiate LicenseChecker, you need to pass in these parameters:</p>
1433
1434 <ul>
1435 <li>The application {@link android.content.Context}</li>
1436 <li>A reference to the Policy implementation to use for the license check. In
1437 most cases, you would use the default Policy implementation provided by the LVL,
1438 ServerManagedPolicy. </li>
1439 <li>The String variable holding your publisher account's public key for
1440 licensing. </li>
1441 </ul>
1442
1443 <p>If you are using ServerManagedPolicy, you won't need to access the class
1444 directly, so you can instantiate it in the LicenseChecker constructor,
1445 as shown in the example below. Note that you need to pass a reference to a new
1446 Obfuscator instance when you construct ServerManagedPolicy.</p>
1447
1448 <p>The example below shows the instantiation of LicenseChecker and
1449 LicenseCheckerCallback from the <code>onCreate()</code> method of an Activity
1450 class. </p>
1451
1452 <pre>public class MainActivity extends Activity {
1453     ...
1454     private LicenseCheckerCallback mLicenseCheckerCallback;
1455     private LicenseChecker mChecker;
1456
1457     &#64;Override
1458     public void onCreate(Bundle savedInstanceState) {
1459         super.onCreate(savedInstanceState);
1460         ...
1461         // Construct the LicenseCheckerCallback. The library calls this when done.
1462         mLicenseCheckerCallback = new MyLicenseCheckerCallback();
1463
1464         // Construct the LicenseChecker with a Policy.
1465         mChecker = new LicenseChecker(
1466             this, new ServerManagedPolicy(this,
1467                 new AESObfuscator(SALT, getPackageName(), deviceId)),
1468             BASE64_PUBLIC_KEY  // Your public licensing key.
1469             );
1470         ...
1471     }
1472 }
1473 </pre>
1474
1475
1476 <p>Note that LicenseChecker calls the LicenseCheckerCallback methods from the UI
1477 thread <em>only</em> if there is valid license response cached locally. If the
1478 license check is sent to the server, the callbacks always originate from the
1479 background thread, even for network errors. </p>
1480
1481
1482 <h4 id="check-access">Call checkAccess() to initiate the license check</h4>
1483
1484 <p>In your main Activity, add a call to the <code>checkAccess()</code> method of the
1485 LicenseChecker instance. In the call, pass a reference to your
1486 LicenseCheckerCallback instance as a parameter. If you need to handle any
1487 special UI effects or state management before the call, you might find it useful
1488 to call <code>checkAccess()</code> from a wrapper method. For example, the LVL
1489 sample application calls <code>checkAccess()</code> from a
1490 <code>doCheck()</code> wrapper method:</p>
1491
1492 <pre>    &#64;Override
1493     public void onCreate(Bundle savedInstanceState) {
1494         super.onCreate(savedInstanceState);
1495         ...
1496         // Call a wrapper method that initiates the license check
1497         doCheck();
1498         ...
1499     }
1500     ...
1501     private void doCheck() {
1502         mCheckLicenseButton.setEnabled(false);
1503         setProgressBarIndeterminateVisibility(true);
1504         mStatusText.setText(R.string.checking_license);
1505         mChecker.checkAccess(mLicenseCheckerCallback);
1506     }
1507 </pre>
1508
1509
1510 <h4 id="account-key">Embed your public key for licensing</h4>
1511
1512 <p>For each publisher account, the Android Market service automatically
1513 generates a  2048-bit RSA public/private key pair that is used exclusively for
1514 licensing. The key pair is uniquely associated with the publisher account and is
1515 shared across all applications that are published through the account. Although
1516 associated with a publisher account, the key pair is <em>not</em> the same as
1517 the key that you use to sign your applications (or derived from it).</p>
1518
1519 <p>The Android Market publisher site exposes the public key for licensing to any
1520 developer signed in to the publisher account, but it keeps the private key
1521 hidden from all users in a secure location. When an application requests a
1522 license check for an application published in your account, the licensing server
1523 signs the license response using the private key of your account's key pair.
1524 When the LVL receives the response, it uses the public key provided by the
1525 application to verify the signature of the license response. </p>
1526
1527 <p>To add licensing to an application, you must obtain your publisher account's
1528 public key for licensing and copy it into your application. Here's how to find
1529 your account's public key for licensing:</p>
1530
1531 <ol>
1532 <li>Go to the Android Market <a
1533 href="http://market.android.com/publish">publisher site</a> and sign in.
1534 Make sure that you sign in to the account from which the application you are
1535 licensing is published (or will be published). </li>
1536 <li>In the account home page, locate the "Edit profile" link and click it. </li>
1537 <li>In the Edit Profile page, locate the "Licensing" pane, shown below. Your
1538 public key for licensing is given in the "Public key" text box. </p>
1539 </ol>
1540
1541 <p>To add the public key to your application, simply copy/paste the key string
1542 from the text box into your application as the value of the String variable
1543 <code>BASE64_PUBLIC_KEY</code>. When you are copying, make sure that you have
1544 selected the entire key string, without omitting any characters. </p>
1545
1546 <p>Here's an example from the LVL sample application:</p>
1547
1548 <pre>    public class MainActivity extends Activity {
1549         private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG ... "; //truncated for this example
1550     ...
1551     }
1552 </pre>
1553
1554 <h4 id="handler-cleanup">Call your LicenseChecker's onDestroy() method
1555 to close IPC connections</h4>
1556
1557 <p>Finally, to let the LVL clean up before your application
1558 {@link android.content.Context} changes, add a call to the LicenseChecker's
1559 <code>onDestroy()</code> method from your Activity's
1560 {@link android.app.Activity#onDestroy()} implementation. The call causes the
1561 LicenseChecker to properly close any open IPC connection to the Android Market
1562 application's ILicensingService and removes any local references to the service
1563 and handler.</p>
1564
1565 <p>Failing to call the LicenseChecker's <code>onDestroy()</code> method
1566 can lead to problems over the lifecycle of your application. For example, if the
1567 user changes screen orientation while a license check is active, the application
1568 {@link android.content.Context} is destroyed. If your application does not
1569 properly close the LicenseChecker's IPC connection, your application will crash
1570 when the response is received. Similarly, if the user exits your application
1571 while a license check is in progress,  your application will crash when the
1572 response is received, unless it has properly called the
1573 LicenseChecker's <code>onDestroy()</code> method to disconnect from the service.
1574 </p>
1575
1576 <p>Here's an example from the sample application included in the LVL, where
1577 <code>mChecker</code> is the LicenseChecker instance:</p>
1578
1579 <pre>    &#64;Override
1580     protected void onDestroy() {
1581         super.onDestroy();
1582         mChecker.onDestroy();
1583         ...
1584     }
1585 </pre>
1586
1587 <p>If you are extending or modifying LicenseChecker, you might also need to call
1588 the LicenseChecker's <code>finishCheck()</code> method, to clean up any open IPC
1589 connections.</p>
1590
1591 <h3 id="impl-DeviceLimiter">Implementing a DeviceLimiter</h3>
1592
1593 <p>In some cases, you might want your Policy to limit the number of actual
1594 devices that are permitted to use a single license. This would prevent a user
1595 from moving a licensed application onto a number of devices and using the
1596 application on those devices under the same account ID. It would also prevent a
1597 user from "sharing" the application by providing the account information
1598 associated with the license to other individuals, who could then sign in to that
1599 account on their devices and access the license to the application. </p>
1600
1601 <p>The LVL supports per-device licensing by providing a
1602 <code>DeviceLimiter</code> interface, which declares a single method,
1603 <code>allowDeviceAccess()</code>. When a LicenseValidator is handling a response
1604 from the licensing server, it calls <code>allowDeviceAccess()</code>, passing a
1605 user ID string extracted from the response.</p>
1606
1607 <p>If you do not want to support device limitation, <strong>no work is
1608 required</strong> &mdash; the LicenseChecker class automatically uses a default
1609 implementation called NullDeviceLimiter. As the name suggests, NullDeviceLimiter
1610 is a "no-op" class whose <code>allowDeviceAccess()</code> method simply returns
1611 a <code>LICENSED</code> response for all users and devices. </p>
1612
1613 <div style="border-left:4px solid #FFCF00;margin:1em;padding: 0 0 0 .5em">
1614 <p><strong>Caution:</strong> Per-device licensing is <em>not recommended for
1615 most applications</em> because:</p>
1616 <ul>
1617 <li>It requires that you provide a backend server to manage a users and devices
1618 mapping, and </li>
1619 <li>It could inadvertently result in a user being denied access to an
1620 application that they have legitimately purchased on another device.</li>
1621 </ul>
1622 </div>
1623
1624
1625 <h2 id="test-env">Setting Up the Testing Environment</h2>
1626
1627 <p>The Android Market publisher site provides configuration tools that let you
1628 and others test licensing on your application before it is published. As you are
1629 implementing licensing, you can make use of the publisher site tools to test
1630 your application's Policy and handling of different licensing responses and
1631 error conditions.</p>
1632
1633 <p>The main components of the test environment for licensing include: </p>
1634
1635 <ul>
1636 <li>A "Test response" configuration in your publisher account that lets you
1637 set the static licensing response returned, when the server processes a
1638 license check for an application uploaded to the publisher account, from a user
1639 signed in to the publisher account or a test account.</li>
1640 <li>An optional set of test accounts that will receive the static test
1641 response when they check the license of an application that you have uploaded
1642 (regardless whether the application is published or not).</li>
1643 <li>A runtime environment for the application that includes the Android Market
1644 application or Google APIs Add-On, on which the user is signed in to the
1645 publisher account or one of the test accounts.</li>
1646 </ul>
1647
1648 <p>Setting up the test environment properly involves:</p>
1649
1650 <ol>
1651 <li><a href="#test-response">Setting static test responses</a> that are returned by the licensing server.</li>
1652 <li><a href="#test-acct-setup">Setting up test accounts</a> as needed.</li>
1653 <li><a href="#acct-signin">Signing in</a> properly to an emulator or device, before initiating a license check test.</li>
1654 </ol>
1655
1656 <p>The sections below provide more information.</p>
1657
1658
1659 <h3 id="test-response">Setting test responses for license checks</h3>
1660
1661 <p>Android Market provides a configuration setting in your publisher account
1662 that lets you override the normal processing of a license check and return a
1663 specified static response code. The setting is for testing only and applies
1664 <em>only</em> to license checks for applications that you have uploaded, made by
1665 any user signed in to an emulator or device using the credentials of the
1666 publisher account or a registered test account. For other users, the server
1667 always processes license checks according to normal rules.  </p>
1668
1669 <p>To set a test response for your account, sign in to your publisher account
1670 and click "Edit Profile". In the Edit Profile page, locate the Test Response
1671 menu in the Licensing panel, shown below. You can select from the full set of
1672 valid server response codes to control the response or condition you want to
1673 test in your application.</p>
1674
1675 <p>In general, you should make sure to test your application's licensing
1676 implementation with every response code available in the Test Response menu.
1677 For a description of the codes, see <a href="#server-response-codes">Server
1678 Response Codes</a> in the Appendix of this document.</p>
1679
1680 <div style="margin-bottom:2em;" id="licensing_test_response">
1681
1682 <img src="{@docRoot}images/licensing_test_response.png" style="text-align:left;margin-bottom:0;" />
1683 <div style="margin:0 2em;padding:0"><strong>Figure 7.</strong> The Licensing
1684 panel of your account's Edit Profile page, showing the Test Accounts field and the
1685 Test Response menu.</div>
1686 </div>
1687
1688 <p>Note that the test response that you configure applies account-wide &mdash;
1689 that is, it applies not to a single application, but to <em>all</em>
1690 applications associated with the publisher account. If you are testing multiple
1691 applications at once, changing the test response will affect all of those
1692 applications on their next license check (if the user is signed into
1693 the emulator or device using the publisher account or a test account).</p>
1694
1695 <p>Before you can successfully receive a test response for a license check,
1696 you must sign in to the device or emulator on which the application
1697 is installed, and from which it is querying the server. Specifically, you must
1698 sign using either your publisher account or one of the test accounts that you
1699 have set up. For more information about test accounts, see the next section.</p>
1700
1701 <p>See <a href="#server-response-codes">Server Response Codes</a> for a list of
1702 test responses available and their meanings. </p>
1703
1704
1705 <h3 id="test-acct-setup">Setting up test accounts</h3>
1706
1707 <p>In some cases, you might want to let multiple teams of developers test
1708 licensing on applications that will ultimately be published through your
1709 publisher account, but without giving them access to your publisher account's
1710 sign-in credentials. To meet that need, the Android Market publisher site lets
1711 you set up one or more optional <em>test accounts</em> &mdash; accounts that are
1712 authorized to query the licensing server and receive static test responses from
1713 your publisher account.</p>
1714
1715 <p>Test accounts are standard Google accounts that you register on your
1716 publisher account, such that they will receive the test response for
1717 applications that you have uploaded. Developers can then sign in to their
1718 devices or emulators using the test account credentials and initiate license
1719 checks from installed applications. When the licensing server receives a license
1720 check from a user of a test account, it returns the static test response
1721 configured for the publisher account.  </p>
1722
1723 <p>Necessarily, there are limitations on the access and permissions given to
1724 users signed in through test accounts, including:</p>
1725
1726 <ul>
1727 <li>Test account users can query the licensing server only for applications that
1728 are already uploaded to the publisher account. </li>
1729 <li>Test account users do not have permission to upload applications to your
1730 publisher account.</li>
1731 <li>Test account users do not have permission to set the publisher account's
1732 static test response.</li>
1733 </ul>
1734
1735 <p>The table below summarizes the differences in capabilities, between the
1736 publisher account, a test account, and any other account.</p>
1737
1738 <p class="table-caption" id="acct-types-table"><strong>Table 1.</strong>
1739 Differences in account types for testing licensing.</p>
1740
1741 <table>
1742 <tr>
1743 <th>Account Type</th>
1744 <th>Can check license before upload?</th>
1745 <th>Can receive test response?</th>
1746 <th>Can set test response?</th>
1747 </tr>
1748
1749 <tr>
1750 <td>Publisher account</td>
1751 <td>Yes</td>
1752 <td>Yes</td>
1753 <td>Yes</td>
1754 </tr>
1755
1756 <tr>
1757 <td>Test account</td>
1758 <td>No</td>
1759 <td>Yes</td>
1760 <td>No</td>
1761 </tr>
1762
1763 <tr>
1764 <td>Other</td>
1765 <td>No</td>
1766 <td>No</td>
1767 <td>No</td>
1768 </tr>
1769 </table>
1770
1771 <h4 id="reg-test-acct">Registering test accounts on the publisher account</h4>
1772
1773 <p>To get started, you need to register each test account in your publisher
1774 account. As shown in <a href="#licensing_test_response">Figure 7</a>, above, you
1775 register test accounts in the Licensing panel of your publisher account's Edit
1776 Profile page. Simply enter the accounts as a comma-delimited list and click
1777 <strong>Save</strong> to save your profile changes.</p>
1778
1779 <p>You can use any Google account as a test account. If you want to own and
1780 control the test accounts, you can create the accounts yourself and distribute
1781 the credentials to your developers or testers.</p>
1782
1783 <h4 id="test-app-upload">Handling application upload and distribution for test
1784 account users</h4>
1785
1786 <p>As mentioned above, users of test accounts can only receive static test
1787 responses for applications that are uploaded to the publisher account. Since
1788 those users do not have permission to upload applications, as the publisher you
1789 will need to work with those users to collect apps for upload and distribute
1790 uploaded apps for testing. You can handle collection and distribution in any way
1791 that is convenient. </p>
1792
1793 <p>Once an application is uploaded and becomes known to the licensing server,
1794 developers and testers can continue modify the application in their local
1795 development environment, without having to upload new versions. You only need to
1796 upload a new version if the local application increments the
1797 <code>versionCode</code> attribute in the manifest file. </p>
1798
1799 <h4 id="test-key">Distributing your public key to test account users</h4>
1800
1801 <p>The licensing server handles static test responses in the normal way,
1802 including signing the license response data, adding extras parameters, and so
1803 on. To support developers who are implementing licensing using test accounts,
1804 rather than the publisher account, you will need to distribute
1805 your public key to them. Developers without access to the publisher site do not
1806 have access to your public key, and without the key they won't be able to
1807 verify license responses. </p>
1808
1809 <p>Note that if you decide to generate a new licensing key pair for your account
1810 for some reason, you need to notify all users of test accounts. For
1811 testers, you can embed the new key in the application package and distribute it
1812 to users. For developers, you will need to distribute the new key to them
1813 directly. </p>
1814
1815
1816 <h3 id="acct-signin">Signing in to an authorized account in the runtime
1817 environment</h3>
1818
1819 <p>The licensing service is designed to determine whether a given user is
1820 licensed to use a given application &mdash; during a license check, the Android
1821 Market application gathers the user ID from the primary account on the system
1822 and sends it to the server, together with the package name of the application
1823 and other information. However, if there is no user information available, the
1824 license check cannot succeed, so the Android Market application terminates the
1825 request and returns an error to the application. </p>
1826
1827 <p>During testing, to ensure that your application can successfully query the
1828 licensing server, you must make sure that you sign in to an account <em>on the
1829 device or emulator</em> using:</p>
1830
1831 <ul>
1832 <li>The credentials of a publisher account, or</li>
1833 <li>The credentials of a test account that is registered with a publisher
1834 account</li>
1835 </ul>
1836
1837
1838 <div class="sidebox-wrapper">
1839 <div class="sidebox">
1840 <h2>Signing in to a Google account on an emulator</h2>
1841
1842 <p>If you are testing licensing on an emulator, you need to sign in to a Google
1843 account on the emulator. If you do not see an option to create a new Google
1844 account, the problem might be that your AVD is running a standard Android system
1845 image, rather than the Google APIs Add-On, API 8 (release 2) or higher. </p>
1846
1847 <p style="margin-top:.5em;">For more information, see <a
1848 href="#runtime-setup">Setting up the runtime environment</a>, above.</p>
1849
1850 </div>
1851 </div>
1852
1853 <p>Signing in using a publisher account offers the advantage of letting your
1854 applications receive static test responses even before the applications are
1855 uploaded to the publisher site.</p>
1856
1857 <p>If you are part of a larger organization or are working with external groups
1858 on applications that will be published through your site, you will more likely
1859 want to distribute test accounts instead, then use those to sign in during
1860 testing. </p>
1861
1862 <p>To sign in on a device or emulator, follow the steps below. The preferred
1863 approach is to sign in as the primary account &mdash; however, if there are
1864 other accounts already in use on the device or emulator, you can create an
1865 additional account and sign in to it using the publisher or test account
1866 credentials.  </p>
1867
1868 <ol>
1869 <li>Open Settings &gt; Accounts &amp; sync</li>
1870 <li>Select <strong>Add Account</strong> and choose to add a "Google" account.
1871 </li>
1872 <li>Select <strong>Next</strong> and then <strong>Sign in</strong>.</li>
1873 <li>Enter the username and password of either the publisher account or a test
1874 account that is registered in the publisher account.</li>
1875 <li>Select <strong>Sign in</strong>. The system signs you in to the new
1876 account.</li>
1877 </ol>
1878
1879 <p>Once you are signed in, you can begin testing licensing in your application
1880 (if you have completed the LVL integration steps above). When your application
1881 initiates a license check, it will receive a response containing the static test
1882 response configured on the publisher account. </p>
1883
1884 <p>Note that, if you are using an emulator, you will need to sign in to the
1885 publisher account or test account each time you wipe data when restarting the
1886 emulator.</p>
1887
1888 <div style="margin:2em 1em 1em 1em;">
1889
1890 <img src="{@docRoot}images/licensing_device_signin.png" style="text-align:left;" />
1891 <div style="margin:.25em 1.25em;padding:0"><strong>Figure 8.</strong> Example of
1892 setting up a Google account on a device or emulator.</div>
1893 </div>
1894
1895 <h2 id="app-obfuscation">Obfuscating Your Application</h2>
1896
1897 <p>To ensure the security of your application, particularly for a paid
1898 application that uses licensing and/or custom constraints and protections, it's
1899 very important to obfuscate your application code. Properly obfuscating your
1900 code makes it more difficult for a malicious user to decompile the application's
1901 bytecode, modify it &mdash; such as by removing the license check &mdash;
1902 and then recompile it.</p>
1903
1904 <p>Several obfuscator programs are available for Android applications, including
1905 <a href="http://proguard.sourceforge.net/">ProGuard</a>, which also offers
1906 code-optimization features. The use of ProGuard or a similar program to obfuscate
1907 your code is <em>strongly recommended</em> for all applications that use Android
1908 Market Licensing. </p>
1909
1910 <h2 id="app-publishing">Publishing a Licensed Application</h2>
1911
1912 <p>When you are finished testing your license implementation, you are ready to
1913 publish the application on Android Market. Follow the normal steps to <a
1914 href="{@docRoot}guide/publishing/preparing.html">prepare</a>, <a
1915 href="{@docRoot}guide/publishing/app-signing.html">sign</a>, and then <a
1916 href="{@docRoot}guide/publishing/publishing.html">publish the application</a>.
1917 </p>
1918
1919 <h4>Removing Copy Protection</h4>
1920
1921 <p>After uploading your licensed application, remember to remove copy protection
1922 from the application, if it is currently used. To check and remove copy
1923 protection, sign in to the publisher site and go the application's upload
1924 details page. In the Publishing options section, make sure that the Copy
1925 Protection radio button selection is "Off".</p>
1926
1927 <h4>Considerations for Free Apps</h4>
1928
1929 <p>Licensing is currently supported only for paid applications. If you already
1930 published your application as free, you won't be able to upload an updated
1931 version that includes licensing (that is, an application that uses the same
1932 package name and that includes the <a href="#manifest-permission">licensing
1933 permission</a>). Here are some points to keep in mind:</p>
1934
1935 <ul>
1936 <li>If you want to offer a free version of your application that provides a
1937 reduced feature set (or that offers the full feature set for trial period), the
1938 free version of your application must not include the licensing permission and
1939 must use a different package name than the paid version of the app.</li>
1940 <li>If you want to offer a paid version of your free application that uses
1941 licensing, you can do so under a new package name.</li>
1942 </ul>
1943
1944 <h2 id="support">Where to Get Support</h2>
1945
1946 <p>If you have questions or encounter problems while implementing or deploying
1947 publishing in your applications, please use the support resources listed in the
1948 table below. By directing your queries to the correct forum, you can get the
1949 support you need more quickly. </p>
1950
1951 <p class="table-caption"><strong>Table 2.</strong> Developer support resources
1952 for Android Market Licensing Service.</p>
1953
1954 <table>
1955
1956 <tr>
1957 <th>Support Type</th>
1958 <th>Resource</th>
1959 <th>Range of Topics</th>
1960 </tr>
1961 <tr>
1962 <td rowspan="2">Development and testing issues</td>
1963 <td>Google Groups: <a
1964 href="http://groups.google.com/group/android-developers">android-developers</a>
1965 </td>
1966 <td rowspan="2">LVL download and integration, library projects, Policy
1967 questions, user experience ideas, handling of responses, Obfuscator, IPC, test
1968 environment setup</td>
1969 </tr>
1970 <tr>
1971 <td>Stack Overflow: <a
1972 href="http://stackoverflow.com/questions/tagged/android">http://stackoverflow.com/questions/tagged/android</a></td>
1973 </tr>
1974 <tr>
1975 <td rowspan="2">Accounts, publishing, and deployment issues</td>
1976 <td><a href="http://www.google.com/support/forum/p/Android+Market">Android
1977 Market Help Forum</a></td>
1978 <td rowspan="2">Publisher accounts, licensing key pair, test accounts, server
1979 responses, test responses, application deployment and results</td>
1980 </tr>
1981 <tr>
1982 <td><a
1983 href="http://market.android.com/support/bin/answer.py?answer=186113">Market
1984 Licensing Support FAQ</a></td>
1985 </tr>
1986 <tr>
1987 <td>LVL issue tracker</td>
1988 <td><a href="http://code.google.com/p/marketlicensing/issues/">Marketlicensing
1989 project issue tracker</a></td>
1990 <td>Bug and issue reports related specifically to the LVL source code classes
1991 and interface implementations</td>
1992 </tr>
1993
1994 </table>
1995
1996 <p>For general information about how to post to the groups listed above, see <a
1997 href="{@docRoot}resources/community-groups.html">Developer Forums</a> document
1998 in the Resources tab.</p>
1999
2000 <h2 id="lvl-summary">Summary of LVL Classes and Interfaces</h2>
2001
2002 <p>The table below lists all of the source files in the License Verification
2003 Library (LVL) available through the Android SDK. All of the files are part of
2004 the <code>com.android.vending.licensing</code> package.</p>
2005
2006 <p class="table-caption"><strong>Table A-1.</strong> Summary of LVL library
2007 classes and interfaces.</p>
2008
2009 <div style="width:99%">
2010 <table width="100%">
2011
2012 <tr>
2013 <th width="15%">Category</th>
2014 <th width="20%">Name</th>
2015 <th width="100%">Description</th>
2016 </tr>
2017
2018 <tr>
2019 <td rowspan="2">License check and result</td>
2020 <td>LicenseChecker</td>
2021 <td>Class that you instantiate (or subclass) to initiate a license check.</td>
2022 </tr>
2023 <tr>
2024 <td><em>LicenseCheckerCallback</em></td>
2025 <td>Interface that you implement to handle result of the license check.</td>
2026 </tr>
2027
2028 <tr>
2029 <td rowspan="3" width="15%">Policy</td>
2030 <td width="20%"><em>Policy</em></td>
2031 <td width="100%">Interface that you implement to determine whether to allow
2032 access to the application, based on the license response. </td>
2033 </tr>
2034 <tr>
2035 <td>ServerManagedPolicy</td>
2036 <td width="100%">Default Policy implementation. Uses settings provided by the
2037 licensing server to manage local storage of license data, license validity,
2038 retry.</td>
2039 </tr>
2040 <tr>
2041 <td>StrictPolicy</td>
2042 <td>Alternative Policy implementation. Enforces licensing based on a direct
2043 license response from the server only. No caching or request retry.</td>
2044 </tr>
2045
2046 <tr>
2047 <td rowspan="2" width="15%">Data obfuscation <br><em>(optional)</em></td>
2048 <td width="20%"><em>Obfuscator</em></td>
2049 <td width="100%">Interface that you implement if you are using a Policy (such as
2050 ServerManagedPolicy) that caches license response data in a persistent store.
2051 Applies an obfuscation algorithm to encode and decode data being written or
2052 read.</td>
2053 </tr>
2054 <tr>
2055 <td>AESObfuscator</td>
2056 <td>Default Obfuscator implementation that uses AES encryption/decryption
2057 algorithm to obfuscate/unobfuscate data.</td>
2058 </tr>
2059
2060 <tr>
2061 <td rowspan="2" width="15%">Device limitation<br><em>(optional)</em></td>
2062 <td width="20%"><em>DeviceLimiter</em></td>
2063 <td width="100%">Interface that you implement if you want to restrict use of an
2064 application to a specific device. Called from LicenseValidator. Implementing
2065 DeviceLimiter is not recommended for most applications because it requires a
2066 backend server and may cause the user to lose access to licensed applications,
2067 unless designed with care.</td>
2068 </tr>
2069 <tr>
2070 <td>NullDeviceLimiter</td>
2071 <td>Default DeviceLimiter implementation that is a no-op (allows access to all
2072 devices).</td>
2073 </tr>
2074
2075 <tr>
2076 <td rowspan="6" width="15%">Library core, no integration needed</td>
2077 <td width="20%">ResponseData</td>
2078 <td width="100%">Class that holds the fields of a license response.</td>
2079 </tr>
2080 <tr>
2081 <td>LicenseValidator</td>
2082 <td>Class that decrypts and verifies a response received from the licensing
2083 server.</td>
2084 </tr>
2085 <tr>
2086 <td>ValidationException</td>
2087 <td>Class that indicates errors that occur when validating the integrity of data
2088 managed by an Obfuscator.</td>
2089 </tr>
2090 <tr>
2091 <td>PreferenceObfuscator</td>
2092 <td>Utility class that writes/reads obfuscated data to the system's
2093 {@link android.content.SharedPreferences} store.</td>
2094 </tr>
2095 <tr>
2096 <td><em>ILicensingService</em></td>
2097 <td>One-way IPC interface over which a license check request is passed to the
2098 Android Market client.</td>
2099 </tr>
2100 <tr>
2101 <td><em>ILicenseResultListener</em></td>
2102 <td>One-way IPC callback implementation over which the application receives an
2103 asynchronous response from the licensing server.</td>
2104 </tr>
2105
2106 </table>
2107 </div>
2108
2109
2110 <h2 id="server-response-codes">Server Response Codes</h2>
2111
2112 <p>The table below lists all of the license response codes supported by the
2113 licensing server. In general, an application should handle all of these response
2114 codes. By default, the LicenseValidator class in the LVL provides all of the
2115 necessary handling of these response codes for you. </p>
2116
2117 <p class="table-caption"><strong>Table A-2.</strong> Summary of response codes
2118 returned by the Android Market server in a license response.</p>
2119
2120 <table>
2121
2122 <tr>
2123 <th>Response Code</th>
2124 <th>Description</th>
2125 <th>Signed?</th>
2126 <th>Extras</th>
2127 <th>Comments</th>
2128 </tr>
2129 <tr>
2130 <td>LICENSED</td>
2131 <td>The application is licensed to the user. The user has purchased the
2132 application or the application is free.</td>
2133 <td>Yes</td>
2134 <td><code>VT</code>,&nbsp;<code>GT</code>, <code>GR</code></td>
2135 <td><em>Allow access according to Policy constraints.</em></td>
2136 </tr>
2137 <tr>
2138 <td>LICENSED_OLD_KEY</td>
2139 <td>The application is licensed to the user, but there is an updated application
2140 version available that is signed with a different key. </td>
2141 <td>Yes </td>
2142 <td><code>VT</code>, <code>GT</code>, <code>GR</code>, <code>UT</code></td>
2143 <td><em>Optionally allow access according to Policy constraints.</em>
2144 <p style="margin-top:.5em;">Can indicate that the key pair used by the installed
2145 application version is invalid or compromised. The application can allow access
2146 if needed or inform the user that an upgrade is available and limit further use
2147 until upgrade.</p>
2148 </td>
2149 </tr>
2150 <tr>
2151 <td>NOT_LICENSED</td>
2152 <td>The application is not licensed to the user.</td>
2153 <td>No</td>
2154 <td></td>
2155 <td><em>Do not allow access.</em></td>
2156 </tr>
2157 <tr>
2158 <td>ERROR_CONTACTING_SERVER</td>
2159 <td>Local error &mdash; the Android Market application was not able to reach the
2160 licensing server, possibly because of network availability problems. </td>
2161 <td>No</td>
2162 <td></td>
2163 <td><em>Retry the license check according to Policy retry limits.</em></td>
2164 </tr>
2165 <tr>
2166 <td>ERROR_SERVER_FAILURE</td>
2167 <td>Server error &mdash; the server could not load the publisher account's key
2168 pair for licensing.</td>
2169 <td>No</td>
2170 <td></td>
2171 <td><em>Retry the license check according to Policy retry limits.</em>
2172 </td>
2173 </tr>
2174 <tr>
2175 <td>ERROR_INVALID_PACKAGE_NAME</td>
2176 <td>Local error &mdash; the application requested a license check for a package
2177 that is not installed on the device. </td>
2178 <td>No </td>
2179 <td></td>
2180 <td><em>Do not retry the license check.</em>
2181 <p style="margin-top:.5em;">Typically caused by a development error.</p>
2182 </td>
2183 </tr>
2184 <tr>
2185 <td>ERROR_NON_MATCHING_UID</td>
2186 <td>Local error &mdash; the application requested a license check for a package
2187 whose UID (package, user ID pair) does not match that of the requesting
2188 application. </td>
2189 <td>No </td>
2190 <td></td>
2191 <td><em>Do not retry the license check.</em>
2192 <p style="margin-top:.5em;">Typically caused by a development error.</p>
2193 </td>
2194 </tr>
2195 <tr>
2196 <td>ERROR_NOT_MARKET_MANAGED</td>
2197 <td>Server error &mdash; the application (package name) was not recognized by
2198 Android Market. </td>
2199 <td>No</td>
2200 <td></td>
2201 <td><em>Do not retry the license check.</em>
2202 <p style="margin-top:.5em;">Can indicate that the application was not published
2203 through Android Market or that there is an development error in the licensing
2204 implementation.</p>
2205 </td>
2206 </tr>
2207
2208 </table>
2209
2210
2211 <h2 id="extras">Server Response Extras</h2>
2212
2213 <p>The licensing server includes several settings in certain types of license
2214 responses, to assist the application and its Policy in managing access to the
2215 application across the 24-hour refund period and other conditions. Specifically,
2216 the server provides recommended values for the application's license validity
2217 period, retry grace period, maximum allowable retry count, and other settings.
2218 The server appends the settings as key-value pairs in the license response
2219 "extras" field. </p>
2220
2221 <p>Any Policy implementation can extract the extras settings from the license
2222 response and use them as needed. The LVL default Policy implementation, <a
2223 href="#ServerManagedPolicy">ServerManagedPolicy</a>, serves as a working
2224 implementation and an illustration of how to obtain, store, and use the
2225 settings. </p>
2226
2227 <p class="table-caption"><strong>Table A-3.</strong> Summary of
2228 license-management settings supplied by the Android Market server in a license
2229 response.</p>
2230
2231 <table>
2232 <tr>
2233 <th>Extra</th><th>Description</th>
2234 </tr>
2235
2236 <tr>
2237   <td>VT</td>
2238   <td>License validity timestamp. Specifies the date/time at which the current
2239 (cached) license response expires and must be rechecked on the licensing server.
2240  </td>
2241 </tr>
2242 <tr>
2243   <td>GT</td>
2244   <td>Grace period timestamp. Specifies the end of the period during which a
2245 Policy may allow access to the application, even though the response status is
2246 RETRY. <p>The value is managed by the server, however a typical value would be 5
2247 or more days.</p></td>
2248 </tr>
2249 <tr>
2250   <td>GR</td>
2251   <td>Maximum retries count. Specifies how many consecutive RETRY license checks
2252 the Policy should allow, before denying the user access to the application.
2253 <p>The value is managed by the server, however a typical value would be "10" or
2254 higher.</p></td>
2255 </tr>
2256 <tr>
2257   <td>UT</td>
2258   <td>Update timestamp. Specifies the day/time when the most recent update to
2259 this application was uploaded and published. <p>The server returns this extra
2260 only for LICENSED_OLD_KEYS responses, to allow the Policy to determine how much
2261 time has elapsed since an update was published with new licensing keys before
2262 denying the user access to the application. </p></td>
2263 </tr>
2264
2265 </table>
2266
2267 <p>The sections below provide more information about the server-provided
2268 settings and how to use them. </p>
2269
2270 <h4>License validity period</h4>
2271
2272 <p>The Android Market licensing server sets a license validity period for all
2273 downloaded applications. The period expresses the interval of time over which an
2274 application's license status should be considered as unchanging and cacheable by
2275 a licensing Policy in the application. The licensing server includes the
2276 validity period in its response to all license checks, appending an
2277 end-of-validity timestamp to the response as an extra under the key "VT". A
2278 Policy can extract the VT key value and use it to conditionally allow access to
2279 the application without rechecking the license, until the validity period
2280 expires. </p>
2281
2282 <p>The license validity signals to a licensing Policy when it must recheck the
2283 licensing status with the licensing server. It is <em>not</em> intended to imply
2284 whether an application is actually licensed for use. That is, when an
2285 application's license validity period expires, this does not mean that the
2286 application is no longer licensed for use &mdash; rather, it indicates only that
2287 the Policy must recheck the licensing status with the server. It follows that,
2288 as long as the license validity period is not expired, it is acceptable for the
2289 Policy to cache the initial license status locally and return the cached license
2290 status instead of sending a new license check to the server.</p>
2291
2292 <p>The licensing server manages the validity period as a means of helping the
2293 application properly enforce licensing across the refund period offered by
2294 Android Market for paid applications. It sets the validity period based on
2295 whether the application was purchased and, if so, how long ago. Specifically,
2296 the server sets a validity period as follows:</p>
2297
2298 <ul>
2299 <li>For a paid application, the server sets the initial license validity period
2300 so that the license response remains valid for as long as the application is
2301 refundable. A licensing Policy in the application may cache the
2302 result of the initial license check and does not need to recheck the license
2303 until the validity period has expired.</li>
2304 <li>When an application is no longer refundable, the server
2305 sets a longer validity period &mdash; typically a number of days. </li>
2306 <li>For a free application, the server sets the validity period to a very high
2307 value (<code>long.MAX_VALUE</code>). This ensures that, provided the Policy has
2308 cached the validity timestamp locally, it will not need to recheck the
2309 license status of the application in the future.</li>
2310 </ul>
2311
2312 <p>The ServerManagedPolicy implementation uses the extracted timestamp
2313 (<code>mValidityTimestamp</code>) as a primary condition for determining whether
2314 to recheck the license status with the server before allowing the user access to
2315 the application. </p>
2316
2317 <h4>Retry period and maximum retry count</h4>
2318
2319 <p>In some cases, system or network conditions can prevent an application's
2320 license check from reaching the licensing server, or prevent the server's
2321 response from reaching the Android Market client application. For example, the
2322 user might launch an application when there is no cell network or data
2323 connection available &mdash; such as when on an airplane &mdash; or when the
2324 network connection is unstable or the cell signal is weak. </p>
2325
2326 <p>When network problems prevent or interrupt a license check, the Android
2327 Market client notifies the application by returning a "RETRY" response code to
2328 the Policy's <code>processServerResponse()</code> method. In the case of system
2329 problems, such as when the application is unable to bind with Android Market's
2330 ILicensingService implementation, the LicenseChecker library itself calls the
2331 Policy <code>processServerResonse()</code> method with a "RETRY" response code.
2332 </p>
2333
2334 <p>In general, the RETRY response code is a signal to the application that an
2335 error has occurred that has prevented a license check from completing. 
2336
2337 <p>The Android Market server helps an application to manage licensing under
2338 error conditions by setting a retry "grace period" and a recommended maximum
2339 retries count. The server includes these values in all license check responses,
2340 appending them as extras under the keys "GT" and "GR". </p>
2341
2342 <p>The application Policy can extract the GT and GR extras and use them to
2343 conditionally allow access to the application, as follows:</p>
2344
2345 <ul>
2346 <li>For a license check that results in a RETRY response, the Policy should
2347 cache the RETRY response code and increment a count of RETRY responses.</li>
2348 <li>The Policy should allow the user to access the application, provided that
2349 either the retry grace period is still active or the maximum retries count has
2350 not been reached.</li>
2351 </ul>
2352
2353 <p>The ServerManagedPolicy uses the server-supplied GT and GR values as
2354 described above. The example below shows the conditional handling of the retry
2355 responses in the <code>allow()</code> method. The count of RETRY responses is
2356 maintained in the <code>processServerResponse()</code> method, not shown. </p>
2357
2358
2359 <pre>    public boolean allowAccess() {
2360         long ts = System.currentTimeMillis();
2361         if (mLastResponse == LicenseResponse.LICENSED) {
2362             // Check if the LICENSED response occurred within the validity timeout.
2363             if (ts &lt;= mValidityTimestamp) {
2364                 // Cached LICENSED response is still valid.
2365                 return true;
2366             }
2367         } else if (mLastResponse == LicenseResponse.RETRY &amp;&amp;
2368                    ts &lt; mLastResponseTime + MILLIS_PER_MINUTE) {
2369             // Only allow access if we are within the retry period or we haven't used up our
2370             // max retries.
2371             return (ts &lt;= mRetryUntil || mRetryCount &lt;= mMaxRetries);
2372         }
2373         return false;
2374     }</pre>
2375