Getting Your Application into Users’ Hands - Tools and Basics - Programming Android (2011)

Programming Android (2011)

Part I. Tools and Basics

Chapter 4. Getting Your Application into Users’ Hands

This chapter covers everything it takes to get your application into users’ hands. Earlier in this book, we told you everything you needed to get started reading example code and creating simple programs. Here, we complete the picture, with all the other operations you need to perform to widely distribute your applications, sell them (if that is your aim), and subsequently get paid by Google, which operates the Android Market.

You may not be ready to put your application into the Android Market, but keeping this process in mind will shape the way you design and implement your application. Commerce has considerations that are distinct from most other aspects of software development, including identifying yourself to the Android Market and to your customers, obtaining permission to use certain APIs, protecting your identity, and preparing your app to be run on a variety of hardware as well as being updated over time.

Application Signing

Application signing, or code signing, enables Android devices, the Android Market, and alternative means of distribution to know which applications originate with the owner of a signing certificate, and to be certain the code has not been modified since it was signed.

Public Key Encryption and Cryptographic Signing

Public key cryptography depends on this mathematical principle: it is easy to multiply large prime numbers together, but it is extremely difficult to factor the product of large primes. The multiplication might take milliseconds, while factoring would take hundreds to millions of years and would require an astronomically large computer.

This asymmetry between multiplication and factoring means that a key made with the product of two large prime numbers can be made public. The knowledge that enables encrypted messages to be decrypted is the pair of large primes that are part of the private key. That means that documents encrypted with the public key are secure, and only the possessor of the private key can decrypt them.

Signing, which is what we will do to Android applications, depends on related properties of public key encryption.

The steps to sign a document are:

1. Compute a unique number—a hash—from the document. This is also known as a message digest.

2. “Encrypt” the message digest with the signer’s private key. This is the signature.

Voilà! You now have a number—a signature—that is tied to the document by the hashing algorithm, and tied to the signer’s private key.

The steps to verify a signed document are:

1. Compute a unique number—a hash—from the document.

2. “Decrypt” the signature using the public key, which should also result in the same number as the hash.

Now you know some interesting facts: the document—in our case, an application—came from the person with the private key corresponding to the public key you used in the verification. And you know that the document was not altered; otherwise, the hash decrypted from the signature would not be the same as the one computed from the document.

Verifying a signature also verifies that the signature was not copied to a different document. Signatures are unalterably tied to the document from which they were created.

TIP

You may have noticed we put the words encrypt and decrypt in quotes when we said the message digest, or hash, is encrypted. This is because it’s not encryption in the way you normally use a public-private key system—to keep prying eyes away from a message by encrypting it with the public key so that only the person with the private key can read the message.

Here, “encrypt” just means “compute a number.” You are not hiding information when you “encrypt” a hash or message digest with a signer’s private key. The reason you use the words encrypt and decrypt is that you get the same hash or message digest when you decrypt with the public key.

Anyone with the public key and a published algorithm can “decrypt”—which is the point in verification: to see that you got the same hash the sender signed, which also proves that the sender is in possession of a private key corresponding to the public key, and proves that the document is what the sender signed.

Because verification can be computed using a public key, your Android system—and any other interested party—can verify that an application was signed with a particular key and that it was not modified since it was signed.

More generally, any electronic document—any set of bits—can be cryptographically signed, and cryptographic signatures, or “digital signatures,” can be used to sign documents in a way that can legally substitute for a person’s handwritten signature.

How Signatures Protect Software Users, Publishers, and Secure Communications

As a user of computer software, you may already have been thinking, “It would be nice to know where my software comes from and that it has not been modified en route to my device.” Signed applications enable you to have this confidence. This is a form of confidence based on cryptographic signatures similar to one you already use. When you browse the Web you already rely on cryptographic signatures to trust that the ecommerce site you are communicating with is authentic, and not a rogue impostor set up to take your money and run. In the case of ecommerce, the client verifies a signature of the server’s certificate using a public key from a certificate authority. Your browser comes with keys from several certificate authorities used for this purpose.

The role of the certificate authority is to consolidate the number of parties you need to trust: you trust your browser vendor to use only keys from reputable certificate authorities, and ecommerce vendors obtain certificates from authorities browser vendors trust. The certificate authorities have a responsibility to verify that the people claiming to be, for example, Amazon.com are, in fact, Amazon.com. Now, when your browser initiates a secure session with Amazon.com, you know two things: your data is secured from eavesdropping by encryption that only the ecommerce vendor’s server can decrypt, and you are reasonably sure that the server you are connecting to is using a certificate issued by a certificate authority to the company you want to communicate with, because the certificate authority has taken steps to assure itself that it issues certificates to known parties.

Self-signed certificates for Android software

In signing Android software, the signing certificate does not have to come from a certificate authority. It can be created by the software publisher—in this case, you. Unlike ecommerce transactions, where you have the additional requirement that you want to ensure that each and every connection your browser makes is to the authentic Amazon.com, perhaps through a link of unknown provenance, the act of using software does not depend as critically on knowing the identity of the signing party.

For organizations considering using a signature issued by a certificate authority, the Google documentation explicitly mentions that there is no need to have your application signed using a certificate authority, and that self-certification is the informal standard for Android applications.

In addition to initially verifying application developer identity, digital signatures on Android are also used during application upgrades to ensure that an application upgrade should be permitted to access files created by an earlier version of the application, and that the upgrading application is not actually a malicious application trying to steal user data.

As long as you are confident that updates to the software come from the same party you obtained the software from in the first place, you can be reasonably sure the programs you are using are safe, and that the publisher of that software is known to the distributor of the software, which is the Android Market.

In addition to the assurance of updates from the original publisher, Android applications are sandboxed and require permissions, as described at http://developer.android.com/guide/topics/security/security.html, to access functionality that could compromise your data or cause chargeable events on your mobile service.

Signing an Application

The concepts behind cryptographic signing are subtle and complex. But the complexity is managed by the SDK tools. When you compile and run Android code on a device or on an emulator, you are running signed code.

Debug certificates

If you have been following the examples in this book and have created an Android project and run it in an emulator or device, you may have noticed you didn’t need to create a certificate and that your application is installable on an Android handset, despite the fact that all Android code must be signed. This convenience is achieved through the use of an automatically created debug certificate. Let’s take a look at the debug certificate.

Look in the android folder in your home folder. There you will find a file named debug.keystore. Using the keytool command, you can find out what is inside this file:

keytool -list -keystore debug.keystore

When you are prompted for a password, enter android. You will see output that looks like this:

Keystore type: JKS

Keystore provider: SUN

Your keystore contains 1 entry

androiddebugkey, May 13, 2010, PrivateKeyEntry,

Certificate fingerprint (MD5): 95:04:04:F4:51:0B:98:46:14:74:58:15:D3:CA:73:CE

The keystore type and provider indicate the keystore is a Java keystore, compatible with the Java Cryptography Architecture and Java classes that enable Android to use code signing and other cryptography tools. More information on the Java Cryptography Architecture is available athttp://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html.

The keytool command is part of the JDK, and is described briefly in keytool and in greater detail at http://developer.android.com/guide/publishing/app-signing.html#cert. Detailed documentation on keytool can also be found athttp://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html.

The last line produced by the list option in keytool is a certificate fingerprint. This is a unique number generated from a key. You will see one way in which this number is used in Google Maps API Keys, where you will use it to get an API key.

This certificate expires in a short enough interval that it cannot be used to distribute Android software other than for testing. Do not mistake the convenience of using a debug certificate for signing software as an indication that you can do without a signing certificate for distributing your applications!

Creating a self-signed certificate

Ready to sign some code for release? First, create a private key using the keytool command thusly:

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name \

-keyalg RSA -keysize 2048 -validity 50000

NOTE

The \ character indicates a line break, and is valid for multiline commands on Unix and Mac OS X. However, you will need to type this all on one line without the \ on Windows.

You can substitute a name of your choice for my-release-key and an alias of your choice for alias_name. The -keysize and -validity parameters should remain as shown in the preceding code.

As shown in the following code, keytool will ask you for a password for the keystore, which you will need to remember when accessing it, and a series of questions about you, your organizational structure, and your location. keytool generates a private key, usable as a signing certificate with a valid life span of about 150 years, and puts it in the file named my-release_key.keystore:

example-user@default-hostname:~$ keytool -genkey -v \

-keystore example-release-key.keystore -alias example_alias_name \

-keyalg RSA -keysize 2048 -validity 50000

Enter keystore password:

Re-enter new password:

What is your first and last name?

[Unknown]: Example Examplenik

What is the name of your organizational unit?

[Unknown]: Example

What is the name of your organization?

[Unknown]: Example

What is the name of your City or Locality?

[Unknown]: Example

What is the name of your State or Province?

[Unknown]: Massachusetts

What is the two-letter country code for this unit?

[Unknown]: US

Is CN=Example Examplenik, OU=Example, O=Example, L=Example, ST=Massachusetts,

C=US correct?

[no]: yes

Generating 2,048 bit RSA key pair and self-signed certificate (SHA1withRSA) with a

validity of 50,000 days for: CN=Example Examplenik, OU=Example, O=Example,

L=Example, ST=Massachusetts, C=US

Enter key password for <example_alias_name>

(RETURN if same as keystore password):

Re-enter new password:

[Storing example-release-key.keystore]

You now have a valid key in a keystore.

Don’t lose it!

While cryptographic digital signatures are, in many ways, more reliable and secure than a handwritten signature, there is one way in which they differ: you can lose your ability to sign a document digitally.

If you lose your signing certificate, you lose your identity to Android devices and the Android Market. This means that, despite the fact that you compile and release the same code as before, you cannot use these newly compiled applications to update applications in the field, since neither Android devices nor the Android Market will recognize you as the same publisher.

Keep multiple backup copies of your signing certificate on multiple types of media, including paper, in multiple locations. And keep those backups secure. If your signing certificate is used by people other than you, they can replace your programs on your customers’ Android devices.

Detailed recommendations from the Android Developers site regarding securing your signing certificate are available at http://developer.android.com/guide/publishing/app-signing.html#secure-key.

TIP

Conversely, your cryptographic signature is your signature solely because it is in your possession. Up to the time you want to publish an Android application and continue to be identified as the publisher, you can generate, use, and discard signatures as much as you like. Don’t be afraid to experiment and learn!

Using a self-signed certificate to sign an application

Now it’s time to sign an application. In Eclipse, select the project of the application you want to sign for release, and select the File→Export command. “Why the ‘export’ command?” you may ask. After all, if you want to give someone your app to try out, you can just give her a copy of the.apk file in the bin directory of the project file hierarchy. It is as arbitrary as it seems: the “export” dialog is a grab bag of functionality, and it was a convenient place to put a procedure that isn’t quite the same as “deploying.”

In this example we use the TestActivity project, but you can use any application—your own, or any project from the examples in this book.

You will be presented with a list of options for exporting, organized into folders. Select the Android folder and select Export Android Application (as shown in Figure 4-1), and click on the Next button.

“Exporting” an Android application

Figure 4-1. “Exporting” an Android application

First, you will see if your application has any errors in configuration that might prevent it from being ready to publish, such as having the debuggable attribute set to true in the manifest. If your app is ready to go, you will see the dialog in Figure 4-2, which displays no errors.

An Android application that has no problems preventing signing and publishing

Figure 4-2. An Android application that has no problems preventing signing and publishing

Subsequent dialog boxes in this multistep sequence focus on signing. The information requested mirrors the information you entered to create your release key in Creating a self-signed certificate.

Next, you will select your keystore, as shown in Figure 4-3. The keystore is the file holding your key.

Selecting the keystore

Figure 4-3. Selecting the keystore

Once you have entered the name of the keystore and the password, click Next and proceed to the next step: selecting the alias of the key, and entering the password for the alias, as shown in Figure 4-4.

Selecting the key alias

Figure 4-4. Selecting the key alias

If you followed the steps in Creating a self-signed certificate, you have only one key, with one alias, in your keystore. Enter the password and click Next. The next step is to specify the destination .apk file and pass some checks to determine if anything else might be wrong with your app. If everything is in order, you will see a screen resembling that shown in Figure 4-5.

When you click Finish you will get a signed .apk file in the specified location.

Selecting the destination, and final checks

Figure 4-5. Selecting the destination, and final checks

Placing an Application for Distribution in the Android Market

Putting an application on the Android Market is remarkably easy. The only prerequisite is that you have a Google account such as a Gmail account. A $25 credit card transaction and some information about yourself are all you need to start uploading applications to the Android Market. Charging for applications and getting paid takes only slightly more information and effort—you don’t even need a website or a corporate entity. (Consulting a lawyer before selling products is a good idea. A lawyer may suggest setting up a corporation and other ways to protect your personal assets from liabilities resulting from commercial activities.)

Becoming an Official Android Developer

The Android Market site is where you become an official Android developer. You can sign up at http://market.android.com/publish/signup.

This site will ask you for identifying information, and will ask you to pay a $25 fee using Google Checkout. This transaction confirms that you have a method of payment, such as a credit card, accepted by Google Checkout. Once you are signed up as a developer, you can use your Google account to log in to the Android Market site.

At this point, Google has reasonable assurance that you are who you say you are: a financial transaction linked to some entity that can pay off a credit card bill. This, combined with the fact that your applications are signed, means Google is also confident that the key you created to sign your applications is in the possession of the person who created the Android Market account for the purpose of uploading applications to the Android Market. If you turn out to be a spammer or a source of badware, you will be shut down, and you will need to find another identity with which to create another Google Checkout account and Android Market account.

Uploading Applications in the Market

The page https://market.android.com/publish/Home#AppEditorPlace is where you upload applications. On it, you will see the latest requirements, and options, for providing information about your application. The page has upload buttons for the application’s .apk file, plus screenshots, videos, and similar content, most of which is optional. When you have an application you would like to leave up on the Market for others to download, you should read the descriptions of the kinds of promotional and explanatory material you can upload, and make use of them. For now, let’s get our app up with the minimum requirements met.

The first thing to do is to upload an .apk file. To try it out, you can use the .apk file you created if you followed along in Using a self-signed certificate to sign an application. Don’t worry that this is not your application, and that it is just an example. You can publish it and then unpublish it right away, as you will see from the instructions in the rest of this section.

Most required information is either part of your profile as an Android developer, or part of the application manifest. As of this writing, the required uploads are two screenshots and an icon image. You will find usable images in the doc folder of the example project. If these requirements change—and the Android Market has changed substantially since it was first introduced—you will find out if you have skipped any required fields or uploads when you click the Publish button at the bottom of the page. Anything you missed will be highlighted, and you can go back and fill in fields or perform uploads as needed to make your application ready for publication.

Click the Publish button.

Congratulations, you have published an Android application. If you go back to https://market.android.com/publish/Home, you will see from the listing of applications that you have one published application (if you have not previously published an application). If you go tohttps://market.android.com and search for, say, your name, the search function should find the application you just published and list it the way a potential customer might see it if he were to find it in the Android Market. From there, you can click through to the application’s page in the Android Market.

Now you can go back to the “Home” page where your application is listed and select it by clicking on the link in the listing. This takes you to a page where the information you entered when you published your app is displayed in such a way that you can modify it and update the application’s listing. You can also unpublish your application from this page, using the Unpublish button at the bottom of the page. Whew! You thought you might start getting customer support inquiries!

An application that has been unpublished is not removed from the market system. It is still listed among your applications, but is not made available for download. You can reverse your decision to unpublish at any time by using the Publish button.

Getting Paid

Google Checkout is the payment mechanism for the Android Market. That is, the Android Market provides a streamlined way to sign up as a Google Checkout merchant.

If you elect to be a publisher of paid applications, you will be directed to a page where you can create a “merchant account.” This may sound a bit intimidating, but Google has made it easy to get paid. You don’t need to form a corporation or get a business bank account.

CAUTION

You should consult a lawyer about forming a corporate entity for your business and you should segregate your business finances from your personal accounts.

The process of getting a merchant account amounts to entering some more information—most importantly your tax ID, which can be your Social Security number—so that income from your sales can be reported.

Getting paid involves linking a bank account to your Google Checkout merchant account. Payments to Google Checkout for sales of your app will be deposited in your bank account. A full description of terms of service, payment terms, and similar information can be found in the sellers’ section of the Google Checkout site, at http://checkout.google.com/support/sell/bin/answer.py?hl=en&answer=113730.

Google Maps API Keys

A Google Maps API key, combined with the keys you use for signing applications, identifies you to Google and enables Google to enforce the terms of service for Google Maps. Google Maps relies on information Google collects and buys at significant expense, and must be protected from misappropriation and other misuse.

If you have been developing an application using the Google Maps API, you will have obtained an API key linked to the debug signature for your application. You can’t use this API key when you ship your application. The Google Maps API, and the requirements for using it, are described inChapter 15.

When you ship your application, you will need a Google Maps API key linked to the signing key you used for distributing your application. That is, you will need a new API key that is made using an MD5 fingerprint of your signing key. Using the keytool command’s list option, you can get the MD5 fingerprint of your signing key thusly:

keytool -list -keystore my-release-key.keystore

You will get this key the same way you got the API key for use with your debug signature, by visiting the Android Maps API Key Signup page at http://code.google.com/android/maps-api-signup.html and using the MD5 fingerprint of your signing key in the form, as shown in Figure 4-6.

Getting a Google Maps API key

Figure 4-6. Getting a Google Maps API key

When you click the Generate API Key button, you will get a web page showing the API key generated from your signing certificate’s fingerprint, as shown in Figure 4-7.

CAUTION

You really have to create your self-signing certificate and Google Maps API keys yourself. You cannot copy them from the screenshots here, you cannot use keys from example code you download, and you cannot use debug keys when releasing a product.

The Android Maps API key generated from your self-signing certificate

Figure 4-7. The Android Maps API key generated from your self-signing certificate

Specifying API-Level Compatibility

At any one time, multiple versions of Android can be available, and not all the prospective users of your application will have the most recent version. By specifying application compatibility in the manifest, you can control which Android systems can install your application, preventing its use in systems that are incompatible with the APIs you are using.

In the example in Making an Android Project, the same API level is specified for the build target as for the Min SDK Version field. This means the program will only run on systems with the specified API level or higher.

Since you can detect the API level at runtime, there may be cases where you want to ship one application for systems with a lower API level than you use, and to test for the API level and only use methods and classes of higher API levels if they are available. In these cases, you would specify a higher build target API level than the Min SDK Version.

Compatibility with Many Kinds of Screens

Android was built to accommodate multiple screen sizes and changes in screen orientation. The best way to accommodate screen size differences among Android devices is to enable your layouts to be as flexible as possible. The images your application uses may not look optimal in very large or unusually small configurations, but it is possible to specify layouts that are usable at screen sizes ranging from the smallest screen of moderate resolution up to a 1920 × 1080 HD display.

In other words, don’t start by designing multiple layouts and multiple graphical assets for different screen sizes. Start by accommodating a wide range of screen sizes well enough for your application to remain usable.

Testing for Screen Size Compatibility

Testing is key to ensuring screen compatibility. The SDK and AVD Manager provides configurations for a range of screen sizes that cover all the smartphones on which Android runs. As described in Making an Android Virtual Device (AVD), you can specify preset and custom screen sizes when creating an Android virtual device.

Resource Qualifiers and Screen Sizes

Once you have layouts that can handle the majority of cases, you may want to improve the way your application looks on specific displays. You may need to use separate layouts in cases where you want to take advantage of greater screen real estate other than by just spreading a layout across the screen (a separate preview pane, for example). In these cases, or in cases of specialized apps that might be used for unusually small displays, you can design layouts for specific situations using resource qualifiers.

Resource qualifiers are a set of naming rules for resource directories that enable you to provide alternative resources for the conditions specified by the qualifier, such as high or low, pixel density, language, country, and certain hardware resource availability. The full range of resource qualifiers is described at http://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources.