Android Developers Blog

The Dalvik VM provides facilities for developers to perform custom class loading. Instead of loading Dalvik executable (“dex”) files from the default location, an application can load them from alternative locations such as internal storage or over the network.

This technique is not for every application; In fact, most do just fine without it. However, there are situations where custom class loading can come in handy. Here are a couple of scenarios:

Big apps can contain more than 64K method references, which is the maximum number of supported in a dex file. To get around this limitation, developers can partition part of the program into multiple secondary dex files, and load them at runtime.

Frameworks can be designed to make their execution logic extensible by dynamic code loading at runtime.

We have created a sample app to demonstrate the partitioning of dex files and runtime class loading. (Note that for reasons discussed below, the app cannot be built with the ADT Eclipse plug-in. Instead, use the included Ant build script. See Readme.txt for detail.)

The app has a simple Activity that invokes a library component to display a Toast. The Activity and its resources are kept in the default dex, whereas the library code is stored in a secondary dex bundled in the APK. This requires a modified build process, which is shown below in detail.

Before the library method can be invoked, the app has to first explicitly load the secondary dex file. Let’s take a look at the relevant moving parts.

Code Organization

The application consists of 3 classes.

com.example.dex.MainActivity: UI component from which the library is invoked

com.example.dex.LibraryInterface: Interface definition for the library

com.example.dex.lib.LibraryProvider: Implementation of the library

The library is packaged in a secondary dex, while the rest of the classes are included in the default (primary) dex file. The “Build process” section below illustrates how to accomplish this. Of course, the packaging decision is dependent on the particular scenario a developer is dealing with.

Class loading and method invocation

The secondary dex file, containing LibraryProvider, is stored as an application asset. First, it has to be copied to a storage location whose path can be supplied to the class loader. The sample app uses the app’s private internal storage area for this purpose. (Technically, external storage would also work, but one has to consider the security implications of keeping application binaries there.)

Below is a snippet from MainActivity where standard file I/O is used to accomplish the copying.

Next, a DexClassLoader is instantiated to load the library from the extracted secondary dex file. There are a couple of ways to invoke methods on classes loaded in this manner. In this sample, the class instance is cast to an interface through which the method is called directly.

Another approach is to invoke methods using the reflection API. The advantage of using reflection is that it doesn’t require the secondary dex file to implement any particular interfaces. However, one should be aware that reflection is verbose and slow.

[This post is by Dianne Hackborn and a supporting cast of thousands; Dianne’s fingerprints can be found all over the Android Application Framework — Tim Bray]

Android 3.2 includes new tools for supporting devices with a wide range of screen sizes. One important result is better support for a new size of screen; what is typically called a “7-inch” tablet. This release also offers several new APIs to simplify developers’ work in adjusting to different screen sizes.

This a long post. We start by discussing the why and how of Android “dp” arithmetic, and the finer points of the screen-size buckets. If you know all that stuff, you can skip down to “Introducing Numeric Selectors” to read about what’s new. We also provide our recommendations for how you can do layout selection in apps targeted at Android 3.2 and higher in a way that should allow you to support the maximum number of device geometries with the minimum amount of effort.

Understanding Screen Densities and the “dp”

Resolution is the actual number of pixels available in the display, density is how many pixels appear within a constant area of the display, and size is the amount of physical space available for displaying your interface. These are interrelated: increase the resolution and density together, and size stays about the same. This is why the 320x480 screen on a G1 and 480x800 screen on a Droid are both the same screen size: the 480x800 screen has more pixels, but it is also higher density.

To remove the size/density calculations from the picture, the Android framework works wherever possible in terms of "dp" units, which are corrected for density. In medium-density ("mdpi") screens, which correspond to the original Android phones, physical pixels are identical to dp's; the devices’ dimensions are 320x480 in either scale. A more recent phone might have physical-pixel dimensions of 480x800 but be a high-density device. The conversion factor from hdpi to mdpi in this case is 1.5, so for a developer's purposes, the device is 320x533 in dp's.

Screen-size Buckets

Android has included support for three screen-size “buckets” since 1.6, based on these “dp” units: “normal” is currently the most popular device format (originally 320x480, more recently higher-density 480x800); “small” is for smaller screens, and “large” is for “substantially larger” screens. Devices that fall in the “large” bucket include the Dell Streak and original 7” Samsung Galaxy Tab. Android 2.3 introduced a new bucket size “xlarge”, in preparation for the approximately-10” tablets (such as the Motorola Xoom) that Android 3.0 was designed to support.

The definitions are:

xlarge screens are at least 960dp x 720dp.

large screens are at least 640dp x 480dp.

normal screens are at least 470dp x 320dp.

small screens are at least 426dp x 320dp. (Android does not currently support screens smaller than this.)

Here are some more examples of how this works with real screens:

A QVGA screen is 320x240 ldpi. Converting to mdpi (a 4/3 scaling factor) gives us 426dp x 320dp; this matches the minimum size above for the small screen bucket.

The Xoom is a typical 10” tablet with a 1280x800 mdpi screen. This places it into the xlarge screen bucket.

The Dell Streak is a 800x480 mdpi screen. This places it into the bottom of the large size bucket.

A typical 7” tablet has a 1024x600 mdpi screen. This also counts as a large screen.

The original Samsung Galaxy Tab is an interesting case. Physically it is a 1024x600 7” screen and thus classified as “large”. However the device configures its screen as hdpi, which means after applying the appropriate ⅔ scaling factor the actual space on the screen is 682dp x 400dp. This actually moves it out of the “large” bucket and into a “normal” screen size. The Tab actually reports that it is “large”; this was a mistake in the framework’s computation of the size for that device that we made. Today no devices should ship like this.

Issues With Buckets

Based on developers’ experience so far, we’re not convinced that this limited set of screen-size buckets gives developers everything they need in adapting to the increasing variety of Android-device shapes and sizes. The primary problem is that the borders between the buckets may not always correspond to either devices available to consumers or to the particular needs of apps.

The “normal” and “xlarge” screen sizes should be fairly straightforward as a target: “normal” screens generally require single panes of information that the user moves between, while “xlarge” screens can comfortably hold multi-pane UIs (even in portrait orientation, with some tightening of the space).

The “small” screen size is really an artifact of the original Android devices having 320x480 screens. 240x320 screens have a shorter aspect ratio, and applications that don’t take this into account can break on them. These days it is good practice to test user interfaces on a small screen to ensure there are no serious problems.

The “large” screen size has been challenging for developers — you will notice that it encompases everything from the Dell Streak to the original Galaxy Tab to 7" tablets in general. Different applications may also reasonably want to take different approaches to these two devices; it is also quite reasonable to want to have different behavior for landscape vs. portrait large devices because landscape has plenty of space for a multi-pane UI, while portrait may not.

Introducing Numeric Selectors

Android 3.2 introduces a new approach to screen sizes, with the goal of making developers' lives easier. We have defined a set of numbers describing device screen sizes, which you can use to select resources or otherwise adjust your UI. We believe that using these will not only reduce developers’ workloads, but future-proof their apps significantly.

The numbers describing the screen size are all in “dp” units (remember that your layout dimensions should also be in dp units so that the system can adjust for screen density). They are:

width dp: the current width available for application layout in “dp” units; changes when the screen switches orientation between landscape and portrait.

height dp: the current height available for application layout in “dp” units; also changes when the screen switches orientation.

smallest width dp: the smallest width available for application layout in “dp” units; this is the smallest width dp that you will ever encounter in any rotation of the display.

Of these, smallest width dp is the most important. It replaces the old screen-size buckets with a continuous range of numbers giving the effective size. This number is based on width because that is fairly universally the driving factor in designing a layout. A UI will often scroll vertically, but have fairly hard constraints on the minimum space it needs horizontally; the available width is also the key factor in determining whether to use a phone-style one-pane layout or tablet-style multi-pane layout.

Typical numbers for screen width dp are:

320: a phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).

480: a tweener tablet like the Streak (480x800 mdpi).

600: a 7” tablet (600x1024).

720: a 10” tablet (720x1280, 800x1280, etc).

Using the New Selectors

When you are designing your UI, the main thing you probably care about is where you switch between a phone-style UI and a tablet-style multi-pane UI. The exact point of this switch will depend on your particular design — maybe you need a full 720dp width for your tablet layout, maybe 600dp is enough, or 480dp, or even some other number between those. Either pick a width and design to it; or after doing your design, find the smallest width it supports.

Now you can select your layout resources for phones vs. tablets using the number you want. For example, if 600dp is the smallest width for your tablet UI, you can do this:

Android will pick the resource that is closest to the device’s “smallest width,” without being larger; so for a hypothetical 700dp x 1200dp tablet, it would pick layout-sw600dp.

If you want to get fancier, you can make a layout that can change when the user switches orientation to the one that best fits in the current available width. This can be of particular use for 7” tablets, where a multi-pane layout is a very tight fit in portrait::

In the setup above, we will always use the phone layout for devices whose smallest width is less than 600dp; for devices whose smallest width is at least 600dp, we will switch between the tablet and large width layouts depending on the current available width.

Selector Precedence

While it is safest to specify multiple configurations like this to avoid potential ambiguity, you can also take advantage of some subtleties of resource matching. For example, the order that resource qualifiers must be specified in the directory name (documented in Providing Resources) is also the order of their “importance.” Earlier ones are more important than later ones. You can take advantage of this to, for example, easily have a landscape orientation specialization for your default layout:

In this case when running on a tablet that is using landscape orientation, the last layout will be used because the “swNNNdp” qualifier is a better match than “port”.

Combinations and Versions

One final thing we need to address is specifying layouts that work on both Android 3.2 and up as well as previous versions of the platform.

Previous versions of the platform will ignore any resources using the new resource qualifiers. This, then, is one approach that will work:

res/layout/main_activity.xml # For phones
res/layout-xlarge/main_activity.xml # For pre-3.2 tablets
res/layout-sw600dp/main_activity.xml # For 3.2 and up tablets

This does require, however, that you have two copies of your tablet layout. One way to avoid this is by defining the tablet layout once as a distinct resource, and then making new versions of the original layout resource that point to it. So the layout resources we would have are:

Of course, you can always simply select the resource to use in code. That is, define two or more resources like “layout/main_activity” and “layout/main_activity_tablet,” and select the one to use in your code based on information in the Configuration object or elsewhere. For example:

Conclusion

We strongly recommend that developers start using the new layout selectors for apps targeted at Android release 3.2 or higher, as we will be doing for Google apps. We think they will make your layout choices easier to express and manage.

Furthermore, we can see a remarkably wide variety of Android-device form factors coming down the pipe. This is a good thing, and will expand the market for your work. These new layout selectors are specifically designed to make it straightforward for you to make your apps run well in a future hardware ecosystem which is full of variety (and surprises).

At Google I/O we announced our plans to add several new capabilities to help developers manage their products more effectively in Android Market. We’re pleased to let you know that the latest of those, multiple APK support, is now available. Multiple APK support is a new publishing option in Android Market for those developers who want extra control over distribution.

Until now, each product listing on Android Market has included a single APK file, a universal payload that is deliverable to all eligible devices — across all platform versions, screen sizes, and chipsets. Broad distribution of a single APK works very well for almost all applications and has the advantage of simplified product maintenance.

With multiple APK support, you can now upload multiple versions of an APK for a single product listing, with each one addressing a different subset of your customers. These APKs are complete, independent APKs that share the same package name, but contain code and resources to target different Android platform versions, screen sizes, or GL texture-compression formats. When users download or purchase your app, Android Market chooses the right APK to deliver based on the characteristics of the device.

When you upload multiple APK files, Android Market handles them as part of a single product listing that aggregates the app details, ratings, and comments across the APKs. All users who browse your app’s details page see the same product with the same description, branding assets, screenshots, video, ratings, and comments. Android Market also aggregates the app’s download statistics, reviews, and billing data across all of the APKs.

Multiple APK support gives you a variety of ways to control app distribution. For example, you could use it to create separate APKs for phones and tablets under the same product listing. You could also use it to take advantage of new APIs or new hardware capabilities without impacting your existing customer base.

To support this new capability, we’ve updated the Developer Console to include controls for uploading and managing APKs in a product listing — we encourage you to take a look. If you’d like to learn more about how multiple APK support works, please read the developer documentation. As always, please feel free to give us feedback on the feature through the Market Help Center.

[This post is by Elliott Hughes, a Software Engineer on the Dalvik team — Tim Bray]

Although most Android apps run entirely on top of Dalvik, some use the Android NDK to include native code using JNI. Native code is harder to get right than Dalvik code, and when you have a bug, it’s often a lot harder to find and fix it. Using JNI is inherently tricky (there’s precious little help from the type system, for example), and JNI functions provide almost no run-time checking. Bear in mind also that the developer console’s crash reporting doesn’t include native crashes, so you don’t even necessarily know how often your native code is crashing.

What CheckJNI can do

To help, there’s CheckJNI. It can catch a number of common errors, and the list is continually increasing. In Gingerbread, for example, CheckJNI can catch all of the following kinds of error:

Arrays: attempting to allocate a negative-sized array.

Bad pointers: passing a bad jarray/jclass/jobject/jstring to a JNI call, or passing a NULL pointer to a JNI call with a non-nullable argument.

Class names: passing anything but the “java/lang/String” style of class name to a JNI call.

Critical calls: making a JNI call between a GetCritical and the corresponding ReleaseCritical.

Direct ByteBuffers: passing bad arguments to NewDirectByteBuffer.

Exceptions: making a JNI call while there’s an exception pending.

JNIEnv*s: using a JNIEnv* from the wrong thread.

jfieldIDs: using a NULL jfieldID, or using a jfieldID to set a field to a value of the wrong type (trying to assign a StringBuilder to a String field, say), or using a jfieldID for a static field to set an instance field or vice versa, or using a jfieldID from one class with instances of another class.

If you’ve written any amount of native code without CheckJNI, you’re probably already wishing you’d known about it. There’s a performance cost to using CheckJNI (which is why it isn’t on all the time for everybody), but it shouldn’t change the behavior in any other way.

Enabling CheckJNI

If you’re using the emulator, CheckJNI is on by default. If you’re working with an Android device, use the following adb command:

adb shell setprop debug.checkjni 1

This won’t affect already-running apps, but any app launched from that point on will have CheckJNI enabled. (Changing the property to any other value or simply rebooting will disable CheckJNI again.) In this case, you’ll see something like this in your logcat output the next time each app starts:

D Late-enabling CheckJNI

If you don’t see this, your app was probably already running; you just need to force stop it and start it again.

Example

Here’s the output you get if you return a byte array from a native method declared to return a String:

Without CheckJNI, you’d just die via SIGSEGV, with none of this output to help you!

New JNI documentation

We’ve also recently added a page of JNI Tips that explains some of the finer points of JNI. If you write native methods, even if CheckJNI isn’t rejecting your code, you should still read that page. It covers everything from correct usage of the JavaVM and JNIEnv types, how to work with native threads, local and global references, dealing with Java exceptions in native code, and much more, including answers to frequently-asked JNI questions.

What CheckJNI can’t do

There are still classes of error that CheckJNI can’t find. Most important amongst these are misuses of local references. CheckJNI can spot if you stash a JNIEnv* somewhere and then reuse it on the wrong thread, but it can’t detect you stashing a local reference (rather than a global reference) and then reusing it in a later native method call. Doing so is invalid, but currently mostly works (at the cost of making life hard for the GC), and we’re still working on getting CheckJNI to spot these mistakes.

We’re hoping to have more checking, including for local reference misuse, in a future release of Android. Start using CheckJNI now, though, and you’ll be able to take advantage of our new checks as they’re added.

Today we are announcing the Android 3.2 platform, an incremental release that adds several new capabilities for users and developers. The new platform includes API changes and the API level is 13.

Here are some of the highlights of Android 3.2:

Optimizations for a wider range of tablets. A variety of refinements across the system ensure a great user experience on a wider range of tablet devices.

Compatibility zoom for fixed-sized apps. A new compatibility display mode gives users a new way to view these apps on larger devices. The mode provides a pixel-scaled alternative to the standard UI stretching, for apps that are not designed to run on larger screen sizes.

Media sync from SD card. On devices that support a removable SD card, users can now load media files directly from the SD card to apps that use them.

Extended screen support API. For developers who want more precise control over their UI across the range of Android-powered devices, the platform’s screen support API is extended with new resource qualifiers and manifest attributes, to also allow targeting screens by their dimensions.

We would also like to remind developers that we recently released new version of the SDK Tools (r12) and of the Eclipse plug-in (ADT 12). We have also updated the NDK to r6.

Visit the Android Developers site for more information about Android 3.2 and other platform versions. To get started developing or testing on the new platform, you can download it into your SDK using the Android SDK Manager.

Earlier this year, we launched several important features aimed at making it easier to find great applications on Android Market on the Web. Today, we're very excited to launch a completely redesigned Android Market client that brings these and other features to phones.

The new Market client is designed to better showcase top apps and games, engage users with an improved UI, and provide a quicker path to downloading or purchasing your products. For developers, the new Android Market client means more opportunities for your products to be merchandised and purchased.

In the home screen, we've created a new promotional page that highlights top content. This page is tiled with colorful graphics that provide instant access to featured apps and games. The page also lets users find their favorite books and movies, which will help drive even more return visits to Market.

To make it fun and easy for users to explore fresh content, we've added our app lists right to the Apps and Games home pages. Users can now quickly flip through these lists by swiping right or left, checking out what other people are downloading in the Top Paid, Top Free, Top Grossing, Top New Paid, Top New Free, and Trending lists. To keep the lists fresh and relevant, we've made them country-specific for many of the top countries.

To help you convert visitors to customers, we’ve made significant changes to the app details page. We've moved the app name and price into a compact action bar at the top of the page, so that users can quickly download or purchase your app. Directly below, users can flip through screen shots by swiping right or left, or scroll down to read your app's description, what's new, reviews, and more. To help you promote your product more effectively, the page now also includes a thumbnail link to your product video which is displayed at full screen when in landscape orientation.

For users who are ready to buy, we've streamlined the click-to-purchase flow so that users can complete a purchase in two clicks from the app details page. During the purchase, users can also see a list of your other apps, to help you cross-sell your other products.

With a great new UI, easy access to app discovery lists, a convenient purchase flow, and more types of content, we believe that the new Market client will become a favorite for users and developers alike.

Watch for the new Market client coming to your phone soon. We've already begun a phased roll-out to phones running Android 2.2 or higher — the update should reach all users worldwide in the coming weeks. We encourage you to try the update as soon as you receive it. Meanwhile, check out the video below for an early look.

Android tablets are becoming more popular, and we're pleased to note that the vast majority of apps resize to the larger screens just fine. To keep the few apps that don't resize well from frustrating users with awkward-looking apps on their tablets, Android 3.2 introduces a screen compatibility mode that makes these apps more usable on tablets. If your app is one of the many that do resize well, however, you should update your app as soon as possible to disable screen compatibility mode so that users experience your app the way you intend.

Beginning with Android 3.2, any app that does not target Android 3.0 (set either android:minSdkVersion or android:targetSdkVersion to “11” or higher) or does not explicitly set android:xlargeScreens="true" in the <supports-screens> element will include a button in the system bar that, when touched, allows users to select between two viewing modes on large-screen devices.

“Stretch to fill screen” is normal layout resizing (using your app’s alternative resources for size and density) and “Zoom to fill screen” is the new screen compatibility mode.

When the user enables this screen compatibility mode, the system no longer resizes your layout to fit the screen. Instead, it runs your app in an emulated normal/mdpi screen (approximately 320dp x 480dp) and scales that up to fill the screen---imagine viewing your app at the size of a phone screen then zooming in about 200%. The effect is that everything is bigger, but also more pixelated, because the system does not resize your layout or use your alternative resources for the current device (the system uses all resources for a normal/mdpi device). Here’s a comparison of what it looks like (screen compatibility mode enabled on the right):

In cases where an app does not properly resize for larger screens, this screen compatibility mode can improve the app’s usability by emulating the app’s phone-style look, but zoomed in to fill the screen on a tablet.

However, most apps (even those that don’t specifically target Honeycomb) look just fine on tablets without screen compatibility mode, due to the use of alternative layouts for different screen sizes and the framework’s flexibility when resizing layouts. Unfortunately, if you haven’t said so in your manifest file, the system doesn’t know that your application properly supports large screens. Thus, if you’ve developed your app against any version lower than Android 3.0 and do not declare support for large screens in your manifest, the system is going to offer users the option to enable screen compatibility mode.

So, if your app is actually designed to resize for large screens, screen compatibility mode is probably an inferior user experience for your app and you should prevent users from using it. The easiest way to make sure that users cannot enable screen compatibility mode for your app is to declare support for xlarge screens in your manifest file’s <supports-screens> element. For example:

Note: If your app is specifically designed to support Android 3.0 and declares either android:minSdkVersion or android:targetSdkVersion with a value of “11” or greater, then your app is already in the clear and screen compatibility mode will not be offered to users, but adding this attribute certainly won’t hurt.

In conclusion, if your app has set the android:minSdkVersion and android:targetSdkVersion both with values less than “11” and you believe your app works well on large and xlarge screens (for example, you’ve tested on a Honeycomb tablet), you should make the above addition to your manifest file in order to disable the new screen compatibility mode.

If your app does not resize properly for large screens, then users might better enjoy your app using screen compatibility mode. However, please follow our guide to Supporting Multiple Screens so that you can also disable screen compatibility mode and provide a user experience that’s optimized for large-screen devices.