Honeycomb <3 usb devices

July 31st, 2011 by Android Dev

We have been developing an e-worksheet style application for the past month now, testing was done on the Acer Iconica A500. So here is a little review about Honeycomb, and the device, with focus on the USB port.
acer

read more

Custom Class Loading in Dalvik

July 30th, 2011 by Android Dev

[This post is by Fred Chung, who’s an Android Developer Advocate — Tim Bray]

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.

  // Before the secondary dex file can be processed by the DexClassLoader,
  // it has to be first copied from asset resource to a storage location.
  File dexInternalStoragePath = new File(getDir("dex", Context.MODE_PRIVATE),
          SECONDARY_DEX_NAME);
  ...
  BufferedInputStream bis = null;
  OutputStream dexWriter = null;

  static final int BUF_SIZE = 8 * 1024;
  try {
      bis = new BufferedInputStream(getAssets().open(SECONDARY_DEX_NAME));
      dexWriter = new BufferedOutputStream(
          new FileOutputStream(dexInternalStoragePath));
      byte[] buf = new byte[BUF_SIZE];
      int len;
      while((len = bis.read(buf, 0, BUF_SIZE)) > 0) {
          dexWriter.write(buf, 0, len);
      }
      dexWriter.close();
      bis.close();

  } catch (. . .) {...}

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.

  // Internal storage where the DexClassLoader writes the optimized dex file to
  final File optimizedDexOutputPath = getDir("outdex", Context.MODE_PRIVATE);

  DexClassLoader cl = new DexClassLoader(dexInternalStoragePath.getAbsolutePath(),
                                         optimizedDexOutputPath.getAbsolutePath(),
                                         null,
                                         getClassLoader());
  Class libProviderClazz = null;
  try {
      // Load the library.
      libProviderClazz =
          cl.loadClass("com.example.dex.lib.LibraryProvider");
      // Cast the return object to the library interface so that the
      // caller can directly invoke methods in the interface.
      // Alternatively, the caller can invoke methods through reflection,
      // which is more verbose.
      LibraryInterface lib = (LibraryInterface) libProviderClazz.newInstance();
      lib.showAwesomeToast(this, "hello");
  } catch (Exception e) { ... }

Build Process

In order to churn out two separate dex files, we need to tweak the standard build process. To do the trick, we simply modify the “-dex” target in the project’s Ant build.xml.

The modified “-dex” target performs the following operations:

  1. Create two staging directories to store .class files to be converted to the default dex and the secondary dex.

  2. Selectively copy .class files from PROJECT_ROOT/bin/classes to the two staging directories.

          <!-- Primary dex to include everything but the concrete library
                     implementation. -->
                <copy todir="${out.classes.absolute.dir}.1" >
                    <fileset dir="${out.classes.absolute.dir}" >
                            <exclude name="com/example/dex/lib/**" />
                    </fileset>
                </copy>
                <!-- Secondary dex to include the concrete library implementation. -->
                <copy todir="${out.classes.absolute.dir}.2" >
                    <fileset dir="${out.classes.absolute.dir}" >
                            <include name="com/example/dex/lib/**" />
                    </fileset>
                </copy>     
  3. Convert .class files from the two staging directories into two separate dex files.

  4. Add the secondary dex file to a jar file, which is the expected input format for the DexClassLoader. Lastly, store the jar file in the “assets” directory of the project.

        <!-- Package the output in the assets directory of the apk. -->
                <jar destfile="${asset.absolute.dir}/secondary_dex.jar"
                       basedir="${out.absolute.dir}/secondary_dex_dir"
                       includes="classes.dex" />

To kick-off the build, you execute ant debug (or release) from the project root directory.

That’s it! In the right situations, dynamic class loading can be quite useful.

New Tools For Managing Screen Sizes

July 30th, 2011 by Android Dev

[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.

Of course, the official write-up on Supporting Multiple Screens is also required reading for people working in this space.

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 320×480 screen on a G1 and 480×800 screen on a Droid are both the same screen size: the 480×800 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 320×480 in either scale. A more recent phone might have physical-pixel dimensions of 480×800 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 320×533 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 320×480, more recently higher-density 480×800); “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 320×240 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 1280×800 mdpi screen. This places it into the xlarge screen bucket.

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

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

  • The original Samsung Galaxy Tab is an interesting case. Physically it is a 1024×600 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 320×480 screens. 240×320 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 (240×320 ldpi, 320×480 mdpi, 480×800 hdpi, etc).

  • 480: a tweener tablet like the Streak (480×800 mdpi).

  • 600: a 7” tablet (600×1024).

  • 720: a 10” tablet (720×1280, 800×1280, 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:

res/layout/main_activity.xml           # For phones
res/layout-sw600dp/main_activity.xml   # For tablets

For the rare case where you want to further customize your UI, for example for 7” vs. 10” tablets, you can define additional smallest widths:

res/layout/main_activity.xml           # For phones
res/layout-sw600dp/main_activity.xml   # For 7” tablets
res/layout-sw720dp/main_activity.xml   # For 10” tablets

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::

res/layout/main_activity.xml          # Single-pane
res/layout-w600dp/main_activity.xml   # Multi-pane when enough width

Or the previous three-layout example could use this to switch to the full UI whenever there is enough width:

res/layout/main_activity.xml                 # For phones
res/layout-sw600dp/main_activity.xml         # Tablets
res/layout-sw600dp-w720dp/main_activity.xml  # Large width

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.

You can also mix in other resource qualifiers:

res/layout/main_activity.xml                 # For phones
res/layout-sw600dp/main_activity.xml         # Tablets
res/layout-sw600dp-port/main_activity.xml    # Tablets when portrait

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:

res/layout/main_activity.xml                 # For phones
res/layout-land/main_activity.xml            # For phones when landscape
res/layout-sw600dp/main_activity.xml         # Tablets

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:

res/layout/main_activity.xml           # For phones
res/layout/main_activity_tablet.xml    # For tablets

To have the original layout point to the tablet version, you put <item> specifications in the appropriate values directories. That is these two files:

res/values-xlarge/layout.xml
res/values-sw600dp/layout.xml

Both would contain the following XML defining the desired resource:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item type="layout" name="main_activty">
            @layout/main_activity_tablet
    </item>
</resources>

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:

public class MyActivity extends Activity {
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate();

        Configuration config = getResources().getConfiguration();
        if (config.smallestScreenWidthDp >= 600) {
            setContentView(R.layout.main_activity_tablet);
        } else {
            setContentView(R.layout.main_activity);
        }
    }
}

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).

Google’s Design Lead Talks About Developing On Ice Cream Sandwich

July 29th, 2011 by Android Dev

This image has no alt text

Android was obviously a hot topic at today’s Mobile First CrunchUp (just ask Chamillionaire). There was a lot of discussion on the difficulty Android developers face when designing for Android. During an earlier panel, Tech Crunch even went as far asking why iPhone apps simply look better than Android apps. With the day winding to a close and during the last roundtable session Mike Isaac from Wired threw out another question to Matias Duarte, Google’s design lead, regarding the next version of Android (Ice Cream Sandwich). He wanted to know how ICS would help developers produce better looking apps across the many form factors Android has to adapt to like Google TV, phones and tablets. Duarte explained that things will continue to get better as the Android platform evolves and becomes more mature.

Here’s a little paraphrased excerpt of Matias Duarte’s describing the next version of Android, Ice Cream Sandwich:

Ice Cream Sandwich will continue the very challenging job of trying to create an embeddable platform that has the flexibility of the web. We’re trying to make one size fits all, and there are different products for different needs. That said, we know it is hard to design in that environment. Ice Cream Sandwich gives you a lot of tools to help you build one app that works more seamlessly across a variety of screen sizes and different form factors. And before that, we’re rolling out tools that help developers focus and optimize. We recently launched features that let you have multiple APKs and specific device targeting. We’re looking to make that transition easier and create really good-looking stuff on Android.

So there you have it, straight from Google’s design lead, Matias Duarte. Developing for multiple form factors will still prove a challenge for devs but Ice Cream Sandwich should help to alleviate some of that pain. I’m just excited to get a “mini” Honeycomb UI on my Android smartphone but lets hope it wont be at the cost of fragmentation.

[Via TechCrunch]


Sensation and EVO 3D Plus Others Get S-Off Thanks to “Revolutionary”

July 29th, 2011 by Android Dev

We’ve mentioned before that, despite having a locked bootloader, development for the HTC Sensation and EVO 3D has progressed at a surprisingly rapid pace. That progression has reached a breakthrough. Through the culmination of efforts by developer groups unrEVOked and AlphaRev, S-OFF has been achieved for several newer HTC devices through a tool called Revolutionary. For those unfamiliar with S-OFF, it represents unlocking a device to enable modifications to elements in its system. In other words, for those looking to truly make your new HTC device your own, the moment is nigh. I say “nigh” simply because the Revolutionary tool is currently directed towards developers and Android users familiar with higher system functions. There’s still enough bugs and unknowns in the process to not release it to the general public. Still, the tool itself represents an impressive achievement and a big step in the development of some of our favorite phones. Click in after the break to see the group’s message, a full list of devices supported, and a link to the tool’s webpage. Here’s to the future! Read More…

Sensation and EVO 3D Plus Others Get S-Off Thanks to “Revolutionary”