Tuesday, November 1, 2011

Android 4.0 Graphics and Animations


[This post is by Romain Guy and Chet Haase, Android engineers who have been known to collaborate on the subject of graphics, UIs, and animation. You can read more from them on their blogs at curious-creature.org and graphics-geek.blogspot.com. — Tim Bray]
Earlier this year, Android 3.0 launched with a new 2D rendering pipeline designed to support hardware acceleration on tablets. With this new pipeline, all drawing operations performed by the UI toolkit are carried out using the GPU.
You’ll be happy to hear that Android 4.0, Ice Cream Sandwich, brings an improved version of the hardware-accelerated 2D rendering pipeline to phones, starting with Galaxy Nexus.

Enabling hardware acceleration

In Android 4.0 (API level 14), hardware acceleration, for the first time, is on by default for all applications. For applications at lower API levels, you can turn it on by adding android:hardwareAccelerated="true" to the<application> tag in your AndroidManifest.xml.
To learn more about the hardware accelerated 2D rendering pipeline visit the official Android developer guide. This guide explains how to control hardware acceleration at various levels, offers several performance tips and tricks and describes in details the new drawing model.
I also encourage you to watch the Android Hardware Accelerated Rendering talk that we gave at Google I/O 2010.

Introducing TextureView

Applications that need to display OpenGL or video content rely today on a special type of UI element calledSurfaceView. This widget works by creating a new window placed behind your application’s window. It then punches a hole through your application’s window to reveal the new window. While this approach is very efficient, since the content of the new window can be refreshed without redrawing the application’s window, it suffers from several important limitations.
Because a SurfaceView’s content does not live in the application’s window, it cannot be transformed (moved, scaled, rotated) efficiently. This makes it difficult to use a SurfaceView inside a ListView or a ScrollView. SurfaceView also cannot interact properly with some features of the UI toolkit such as fading edges or View.setAlpha().
To solve these problems, Android 4.0 introduces a new widget called TextureView that relies on the hardware accelerated 2D rendering pipeline and SurfaceTexture. TextureView offers the same capabilities as SurfaceView but, unlike SurfaceView, behaves as a regular view. You can for instance use a TextureView to display an OpenGL scene or a video stream. The TextureView itself can be animated, scrolled, etc.
The following piece of code creates a TextureView to display the video preview from the default camera. The TextureView itself is rotated 45 degrees and semi-transparent.
public class TextureViewActivity extends Activity implements TextureView.SurfaceTextureListener {
    private Camera mCamera;
    private TextureView mTextureView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTextureView = new TextureView(this);
        mTextureView.setSurfaceTextureListener(this);

        setContentView(mTextureView);
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        mCamera = Camera.open();

        Camera.Size previewSize = mCamera.getParameters().getPreviewSize();
        mTextureView.setLayoutParams(new FrameLayout.LayoutParams(
                previewSize.width, previewSize.height, Gravity.CENTER));

        try {
            mCamera.setPreviewTexture(surface);
        } catch (IOException t) {
        }

        mCamera.startPreview();
        
        mTextureView.setAlpha(0.5f);
        mTextureView.setRotation(45.0f);
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
        // Ignored, the Camera does all the work for us
    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        mCamera.stopPreview();
        mCamera.release();
        return true;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {
        // Called whenever a new frame is available and displayed in the TextureView
    }
}
A TextureView can just as easily be used to embed an OpenGL scene in your application. As of Android 4.0,eglCreateWindowSurface() can be used to render into a SurfaceTexture object.

Animation

There were minor improvements in Android 4.0 to some of the new animation facilities that were added in the 3.x releases.
First, if you're new to the new android.animation package and classes added in 3.0 and 3.1, you might want to readAnimation in Honeycomb and Introducing ViewPropertyAnimator. These articles discuss the new APIs added in 3.0 that make animation in Android easier, more powerful, and more flexible. The Android 4.0 improvements discussed below are small additions to these core facilities.

Properties

One of the constraints of the Java programming language is the lack of “properties”. There is no way to refer generically to a field or a setter/getter of an object. As long as you know what kind of object you have, this is not a problem, because you then know the set of fields and methods that you can call. But if someone passes you some subclass of Object and you'd like to get or set some value “foo” on it, you're out of luck. You can use reflection or JNI to get access to the foo field/methods, but there is no way to refer directly to a field or a method unless you know the instance type of the object that has that field/method on it.
This is a constraint that the new animation system works within. Its whole job, you might say, is to get and set values on generic objects that it's been told about. If someone wants to animate the alpha property on a View, they tell the system the target object and the name of that field (“alpha”), and the animation system uses JNI to figure out which method(s) act on a field of that name. Basically, it looks for setAlpha() and, sometimes, getAlpha() methods. Then when an animation frame occurs, it calculates the new value and passes it into the setter method that it found.
This seems like a lot of work for what it does, but there's really no way around it. Unless the animation system were specific to View objects, there's no way that it could know that the target object has appropriate setter/getter methods. And even if it did, there's still no way for callers that construct the animations to tell the animator about the property named “alpha”; there are no function handles like there are in other languages, and there's no way to reference a public field either. (I'm ignoring Reflection here, which has Method and Field objects, because this approach requires much more overhead and processing than the simple function/field references of other languages).
If only there were a way to refer to these properties and to get/set them on generic objects...
Now there is. There is a new Property object in the android.util package that does exactly this. This class offers aset() and a get() method. So if someone hands you a Property object, you can safely call the set() and get()methods without knowing anything about the target object and it will do the job. Moreover, it will do it much more efficiently than the current JNI or reflection approaches because it can, depending on the implementation of it, set a field or call a method on the target object directly. For example, the new ALPHA property on View calls setAlpha() on the View object.
The Property class is a generic utility that can be used anywhere, not just in animations. But it's animations that benefit enormously from it, in their ability to handle properties in a type-safe and efficient manner.
For example prior to Android 4.0, you might construct a fade-out animation on some object myView like this:
ObjectAnimator anim = ObjectAnimator.ofFloat(myView, "alpha", 0);
In Android 4.0, you can use the new ALPHA object on View to construct a Property-based animator instead:
ObjectAnimator anim = ObjectAnimator.ofFloat(myView, View.ALPHA, 0);

ViewPropertyAnimator Additions

There were minor API additions to the ViewPropertyAnimator class (introduced in Android 3.1) which make this class more flexible and powerful:
  • cancel(): You can now cancel() a running ViewPropertyAnimator.
  • setStartDelay(): You can now set a startDelay on the ViewPropertyAnimator, just like the startDelay of the other Animator classes.
  • start(): ViewPropertyAnimators start automatically, but they do so on the next animation frame handled. This allows them to collect several requests and bundle them together, which is much more efficient and makes it easier to synchronize multiple animations together. However, if you just want to run a single animation, or want to make sure it starts immediately, at the time of construction, you can call start() to avoid that intervening delay.

LayoutTransition

LayoutTransition (introduced in Android 3.0) continues to provide functionality that makes some kinds of animations easier, specifically when adding, removing, hiding, and showing views. For example, either this snippet in a layout file:
<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true"
    android:id="@+id/container">
Or this code added at runtime:
 container.setLayoutTransition(new LayoutTransition());
will result in a container that animates the visibility of its children views. So when a view is added to the container, the other children will animate out of the way and then the new one will fade in. Similarly, removing a child from the container will fade it out and then animate the other children around to their final places and sizes.
You can customize the animations and timing behavior of a LayoutTransition object, but the code above allows a very easy way to get reasonable default animation behavior.
One of the constraints in the pre-4.0 version of the class was that it did not account for changes in the bounds of the parent hierarchy. So, for example, if a LinearLayout with horizontal orientation has a layout_width of wrap_content and you want to run a transition that removes an item from that layout, then you might notice the parent snapping to the end size and clipping its children instead of animating all of them into their new positions. The new approach (enabled by default, but disabled by a call to setAnimateParentHierarchy(false)) also animates the layout bounds and scrolling values of the parent layout and its parents, all the way up the view hierarchy. This allows LayoutTransition to account for all layout-related changes due to that view being added or removed from its transitioning container.

Conclusion

The Android 3.0 release saw huge improvements in the visual capabilities of the platform, as we started enabling hardware acceleration and providing new, more flexible animation capabilities. Android 4.0 continues this trend as we continue to work hard on improving the performance, features, and usability of the Android APIs. We’re not done yet, but the enhancements in this release should help you create more exciting Android experiences and applications.

Introducing Android WebDriver

[This post is by Dounia Berrada, an engineer on the EngTools team. — Tim Bray]
Selenium WebDriver is a browser automation tool which provides a lightweight and elegant way for testing web apps. Selenium WebDriver is now available as an SDK extra in the Android SDK, and supports 2.3 (Gingerbread) and onwards!
Whether or not your site is optimized for mobile browsers, you can be sure that users will be accessing it from their phones and tablets. WebDriver makes it easy to write automated tests that ensure your site works correctly when viewed from the Android browser. We’ll walk you through some basics about WebDriver and look at it in action.

WebDriver Basics

WebDriver tests are end-to-end tests that exercise the web application just like a real user would. WebDriver models user interactions with a web page such as finger flicks, finger scrolls and long presses. It can rotate the display and interact with HTML5 features such as local storage, session storage and the application cache. Those tests run as part of an Android tests project and are based on Junit. They can be launched from Eclipse or the command line. WebDriver tests can be wired with a continuous integration system and can run on phone and tablet emulators or real devices. Once the test starts, WebDriver opens a WebView configured like the Android browser and runs the tests against it.
WebDriver is an Android SDK extra and can be installed following these instructions. Once you’ve done that you’ll be ready to write tests! There is a comprehensive WebDriver user guide on the Selenium site, but let’s start with a basic example using www.google.com to give you a taste of what’s possible.

Getting Started

First, create an Android project containing an empty activity with no layout.
public class SimpleAppActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}
Then create the Android test project that will contain the tests. WebDriver will create the WebView and set the layout automatically in the main Activity.
Let’s write a test that opens the Google home page on Android and issues a query for “weather in San Francisco”. The test will verify that Google returns search results, and that the first result returned is giving the weather in San Francisco.
public class SimpleGoogleTest extends ActivityInstrumentationTestCase2<SimpleAppActivity> {

    public void testGoogleShouldWork() {
      // Create a WebDriver instance with the activity in which we want the test to run
      WebDriver driver = new AndroidDriver(getActivity());
      // Let’s open a web page
      driver.get("http://www.google.com");

      // Lookup for the search box by its name
      WebElement searchBox = driver.findElement(By.name("q"));

      // Enter a search query and submit
      searchBox.sendKeys("weather in san francisco");
      searchBox.submit();

      // Making sure that Google shows 11 results
      WebElement resultSection = driver.findElement(By.id("ires"));
      List<WebElement> searchResults = resultSection.findElements(By.tagName("li"));
      assertEquals(11, searchResults.size());

      // Let’s ensure that the first result shown is the weather widget
      WebElement weatherWidget = searchResults.get(0);
      assertTrue(weatherWidget.getText().contains("Weather for San Francisco, CA"));
    }
}
Now let’s see our test in action! WebDriver will create a WebView with the same configuration as the Android browser in the main UI thread, i.e. the activity thread. The activity will display the WebView on the screen, allowing you to see your web application as the test code is executing.

Interaction Testing

We’ve mentioned that WebDriver supports creating advanced gestures to interact with the device. Let’s use WebDriver to throw an image across the screen by flicking horizontally, and ensure that the next image in the gallery is displayed.
WebElement toFlick = driver.findElement(By.id("image"));
// 400 pixels left at normal speed
Action flick = getBuilder(driver).flick(toFlick, 0, -400, FlickAction.SPEED_NORMAL)
        .build();
flick.perform();
WebElement secondImage = driver.findElement(“secondImage”);
assertTrue(secondImage.isDisplayed());
Now, let’s rotate the screen and ensure that the image displayed on screen is resized.
assertEquals(landscapeSize, secondImage.getSize())
((Rotatable) driver).rotate(ScreenOrientation.PORTRAIT);
assertEquals(portraitSize, secondImage.getSize());
What if your test reveals a bug? You can easily take a screenshot for help in future debugging:
File tempFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

Find Out More

If this has whetted your appetite and you’d like to know more, go ahead and install the Android WebDriver, take a look at the documentation on the Selenium project’s wiki, or just browse the javadocs. For questions and feedback not only of the Android WebDriver but also its desktop brethren, please join webdriver@googlegroups.com. For announcements keep an eye on http://seleniumhq.wordpress.com/.

Changes to Library Projects in Android SDK Tools, r14

Last week, we released the SDK for Android 4.0 and a new set of developer tools, now in revision 14. The updated tools include a lot of build changes, many that improve build performance. Also included is an under-the-hood change in how libraries are used by main projects — a first step in improving library support and code reusability. While the change should have little impact on existing projects, some developers have had issues when migrating to the updated tools. Please read below for more information about the change to library projects and how to solve migration issues.
Previously, library projects were handled as extra resource and source code folders to be used when compiling the resources and the application’s source respectively. While this worked fine for most cases, there were two issues.
1. Developers asked us for the ability to distribute a library as a single jar file that included both compiled code and resources. The nature of Android resources, with their compiled IDs prevented this.
2. The implementation of the library projects was extremely fragile in Eclipse. Adding extra source folders outside of the project folders is non-trivial when it needs to be handled automatically, in a way that doesn’t expose a user’s local installation path (which is required for people working in teams through a source control system such as SVN or git).
For r14, we decided to fix both issues at once, by moving to a compiled-code based library mechanism. This solves the implementation fragility in Eclipse and will allow us to, later, enable distribution of libraries as a single jar file.
As you might have seen in the release notes, moving to this new mechanism can affect existing projects in some cases, but there are simple fixes.
The first impact of this change is that the new library project requires the resource IDs generated by libraries to be non final. This prevents the Java compiler from inlining the values in the library code, and therefore prevents usage of theswitch statement in the library code. To address such occurrences in your code, Eclipse provides a refactoring action to convert from switch statements to if/else (see here).
Second, some projects may not have been properly migrated to the new mechanism, resulting in projects that fail to compile, with errors such as duplicated classes being added in the dex build step. ADT 14 should have migrated older projects to the new mechanism but the fragility of the old mechanism may have prevented it from happening. This makes projects reference the libraries twice, using both the old and new mechanisms, which then triggers the libraries classes being packaged twice. If you see this in your projects, look in the Package Explorer for extraneous source folders named with the pattern <libraryname>_src. The screenshot to the right shows an example of this.
To fix the project, you must remove the extraneous source folders with the following steps:
  • Right click source folder and choose Build Path > Remove from Build path
  • A dialog will pop up. In it, make sure to check “Also unlink the folder from the project” to completely remove the folder.
With this change to library projects, we pave the way to better support for reusable components. We will continue working to make components easier to create, work with, and manage. Our goal is to make it easy for developers to create apps with great user experiences that easily adapt to all form factors.
Some developers have also told us that they only use library projects internally, that they don’t need to distribute binary versions and would prefer to continue with a source-based mechanism. We are investigating how we could support this alongside the new mechanism.
Finally, I wanted to point out that we are tracking a few known issues (and workaround for them) in the current r14 tools at this page: http://tools.android.com/knownissues.
We are working on a tools update that will include fixes for most of these. We are hoping to have it out shortly.

New Public APIs in ICS

Since Android is open-source, anyone can look at the code and see how it works inside. If you do this, you’ll notice that most but not all of the APIs are publicly documented.
If they’re publicly documented, they’re part of what we consider the Android Application Framework. This means their tests appear in the Compatibility Test Suite (CTS) so that our hardware partners have to prove that the APIs work, and that we promise to try very hard not to change them and thus break your code.
In almost every case, there’s only one reason for leaving APIs undocumented: We’re not sure that what we have now is the best solution, and we think we might have to improve it, and we’re not prepared to make those commitments to testing and preservation.
We’re not claiming that they’re “Private” or “Secret” — How could they be, when anyone in the world can discover them? We’re also not claiming they’re forbidden: If you use them, your code will compile and probably run. And in fact we know of quite a few apps out there whose developers have used undocumented APIs, often to good effect. It’s hard to get too upset about this in cases where there’s a useful API that we haven’t gotten around to stabilizing.
But the developers who use those APIs have to be prepared to deal with the situation that arises when we move them from the undocumented outside into the Android Application Framework. Fortunately, this is reasonably straightforward. Also we take a close look at Android Market, using our in-house analytics tools, to get a feel for the impact when we know one of these changes is coming.
There are a few such changes coming up in the Android 4.0 “Ice Cream Sandwich” (ICS) release of Android. We wanted to take the opportunity to combine these words on undocumented APIs with some specifics about the changes.

Calendars

Let’s start with the good news: As of ICS, the Android Framework will include a fully-worked-out set of APIs for accessing Calendar data. You can guess the bad news: Quite a few developers have built apps (including many good ones) using the undocumented Calendar APIs, some using fairly low-level access to the calendar database. Unfortunately, these integrations were unsupported, and prone to breakage by platform updates or OEM customization of calendar features.
We want to see lots of good calendar apps and extensions that work reliably across Android devices, and aren't broken by platform updates. So we decided to create a clean API, including a comprehensive set of Intents, to manage calendar data in ICS. Now anyone can code against these new APIs and know that Android is committed to supporting them, and that partners have to support these APIs as part of CTS.
Once the new APIs arrive, you’re going to have to update your apps before they’ll run correctly on ICS while still working on older releases. There are a variety of techniques for doing that, many of which have been featured on this blog, including reflection and lazy loading. Recently, we introduced Multiple-APK support, which could also be used to help with this sort of transition.

Text To Speech

Android has never really had a text-to-speech API at the Framework level, but there was unofficial access at the C++ level. With ICS, we will have a fully-thought-through application-level API running on Dalvik, so you can access it with ordinary Java-language application code.
The old C++ API will no longer be supported, but we’ll have a compatibility layer that you can use to bridge from it to the new API. We think it should be easy to update for ICS with very little work.

Doing the Right Thing

We recognize that this means some work for developers affected by these changes, but we’re confident that Android programs in general, and both Calendar and TTS apps in particular, will come out ahead. And we also think that most developers know that when they use undocumented APIs, they’re making a commitment to doing the right thing when those APIs change.

Android 4.0 Platform and Updated SDK Tools

ICS logo
Today we are announcing Android 4.0, Ice Cream Sandwich — a new version of the platform that brings a refined, unified user experience for phones, tablets, and more.
Android 4.0 builds on the things people love most about Android — efficient multitasking, rich notifications, customizable home screens, resizable widgets, and deep interactivity — and adds powerful new ways of communicating and sharing. It includes many great features for users, including social and sharing integration, network data usage control, innovative connectivity and camera options, and an updated set of standard apps.
For developers, Android 4.0 introduces many new capabilities and APIs. Here are some highlights:

Unified UI toolkit: A single set of UI components, styles, and capabilities for phones, tablets, and other devices.
Rich communication and sharing: New social and calendar APIs, Android Beam for NFC-based instant sharing, Wi-Fi Direct support, Bluetooth Health Device Profile support.
Deep interactivity and customization: Improved notifications, lockscreen with camera and music controls, and improved app management in the launcher.
New graphics, camera, and media capabilities: Image and video effects, precise camera metering and face detection, new media codecs and containers.
Interface and input: Hardware-accelerated 2D drawing, new grid-based layout, improved soft keyboard, spell-checker API, stylus input support, and better mouse support.
Improved accessibility: New accessibility APIs and text-to-speech APIs for writing new engines.
Enhancements for enterprise: Keychain and VPN APIs for managing credentials and connections, a new administrator policy for disabling the camera.
For a complete overview of what’s new for users and developers, please read the Android 4.0 Platform Highlights.
Alongside the new Android platform, we are releasing new versions of the SDK Tools (r14) and ADT Plugin (14.0) for Eclipse. Among the highlights are:
  • Improved build performance in Ant and Eclipse
  • Improved layout and XML editors
To get started developing on Android 4.0, visit the Android Developers site for information about the Android 4.0 platform, the SDK Tools, and the ADT Plugin.
If you have already developed and published apps, we encourage you to download the Android 4.0 platform now, to begin testing your app before devices arrive in stores.

Check out the video below for a closer look at Android 4.0 in action.

Android Market Featured-Image Guidelines

[This post is by Natascha Bock, a Product Marketing Manager on Android. — Tim Bray]
With the latest Android Market update, our editorial team can use your 1024 x 500 “Featured Image” to promote your app on tablets, phones, and the Web. The image can be used on the home page on all versions of Android Market (Web, tablet and phone), on your product page in the Web and tablet versions, and on current and future top-level Android Market pages on phones.
Creating a Featured Image that will do a great job of highlighting your app requires special design consideration.

Not Really Optional

While many promotional assets are listed as “optional” for the publishing site, we strongly recommend treating them as required. To start with, a Featured Image is required if your app is to be featured anywhere within Android Market. They’re a good idea anyhow; they enhance your product page, making your game or app more attractive to end-users (and more likely to be considered for featuring by our editorial team).
There’s nothing optional about the size, either; it has to be 1024 x 500 pixels.

Do’s and Dont’s

Your graphic is not an ad, it’s a teaser. It’s a place for bold, creative promotional images.
Vivid background colors work best. Black and white are problems because those are the backgrounds used by the mobile-device and Web versions of Android Market.
Limit Text to your app name and maybe a few additional descriptive words. Anything else will be unreadable on phones, anyhow.
Do: Make the graphic fun
and enticing.
Don't: Create a text-heavy
advertising-style graphic.
Do: Use colors that stand out on
black or white backgrounds.
Don't: Let the graphic fade into
the background.
Do: Promote your brand prominently.
Don't: Overload the graphic with details.

Scaling

Your image has to be designed to scale; it will need to look good both in a full-size Web browser and on a little handset. You can rely on the aspect ratio being constant, but not the size. Here’s a tip: Try resizing your image down to 1 inch in width. If it still looks good and conveys your brand message, you have a winner.
On the Web:

On a tablet:

On a big phone:

On a small phone:

More Dont’s

  • Device imagery is tempting, but becomes dated fast, and may be inappropriate if your user’s device looks entirely different.
  • In-app screenshots are inappropriate because your product page already includes a place for these.
  • Just using your app icon is a failure of imagination. You have more room; put it to good use!

Consider the Context

Given the size of the form factor, the phone is the most challenging channel for your image. Below we have both the “good” and “bad” sample images in that context:

Don’t Forget

A 1024 x 500 Featured Image is required for feature placement consideration. Don't miss out on the opportunity!

Android’s HTTP Clients

Jesse Wilson
[This post is by Jesse Wilson from the Dalvik team. —Tim Bray]
Most network-connected Android apps will use HTTP to send and receive data. Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client. Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.

Apache HTTP Client

DefaultHttpClient and its sibling AndroidHttpClient are extensible HTTP clients suitable for web browsers. They have large and flexible APIs. Their implementation is stable and they have few bugs.
But the large size of this API makes it difficult for us to improve it without breaking compatibility. The Android team is not actively working on Apache HTTP Client.

HttpURLConnection

HttpURLConnection is a general-purpose, lightweight HTTP client suitable for most applications. This class has humble beginnings, but its focused API has made it easy for us to improve steadily.
Prior to Froyo, HttpURLConnection had some frustrating bugs. In particular, calling close() on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling:
private void disableConnectionReuseIfNecessary() {
    // HTTP connection reuse which was buggy pre-froyo
    if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
        System.setProperty("http.keepAlive", "false");
    }
}
In Gingerbread, we added transparent response compression. HttpURLConnection will automatically add this header to outgoing requests, and handle the corresponding response:
Accept-Encoding: gzip
Take advantage of this by configuring your Web server to compress responses for clients that can support it. If response compression is problematic, the class documentation shows how to disable it.
Since HTTP’s Content-Length header returns the compressed size, it is an error to use getContentLength() to size buffers for the uncompressed data. Instead, read bytes from the response until InputStream.read() returns -1.
We also made several improvements to HTTPS in Gingerbread. HttpsURLConnection attempts to connect with Server Name Indication (SNI) which allows multiple HTTPS hosts to share an IP address. It also enables compression and session tickets. Should the connection fail, it is automatically retried without these features. This makes HttpsURLConnection efficient when connecting to up-to-date servers, without breaking compatibility with older ones.
In Ice Cream Sandwich, we are adding a response cache. With the cache installed, HTTP requests will be satisfied in one of three ways:
  • Fully cached responses are served directly from local storage. Because no network connection needs to be made such responses are available immediately.
  • Conditionally cached responses must have their freshness validated by the webserver. The client sends a request like “Give me /foo.png if it changed since yesterday” and the server replies with either the updated content or a304 Not Modified status. If the content is unchanged it will not be downloaded!
  • Uncached responses are served from the web. These responses will get stored in the response cache for later.
Use reflection to enable HTTP response caching on devices that support it. This sample code will turn on the response cache on Ice Cream Sandwich without affecting earlier releases:
private void enableHttpResponseCache() {
    try {
        long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
        File httpCacheDir = new File(getCacheDir(), "http");
        Class.forName("android.net.http.HttpResponseCache")
            .getMethod("install", File.class, long.class)
            .invoke(null, httpCacheDir, httpCacheSize);
    } catch (Exception httpResponseCacheNotAvailable) {
    }
}
You should also configure your Web server to set cache headers on its HTTP responses.

Which client is best?

Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.
For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. New applications should use HttpURLConnection; it is where we will be spending our energy going forward.

Google I/O 2011: Android Open Accessory API and Development Kit (ADK)

Google I/O 2011: Android + App Engine: A Developer's Dream Combination


: Designing and Implementing Android UIs for Phones and Tablets


Google I/O 2011: Android Protips: Advanced Topics for Expert Android App Developers


Google I/O 2011: Android Development Tools


Darood Pak...


Way to offer Namaz...


Monday, October 31, 2011

Google I/O 2011: Designing and Implementing Android UIs for Phones and Tablets


Android Testing

The Android development environment includes an integrated testing framework that helps you test all aspects of your application.

Fundamentals

To start learning how to use the framework to create tests for your applications, please read the topic Testing Fundamentals.

Concepts

  • Activity Testing focuses on testing activities. It describes how instrumentation allows you to control activities outside the normal application lifecycle. It also lists activity-specific features you should test, and it provides tips for testing Android user interfaces.
  • Content Provider Testing focuses on testing content providers. It describes the mock system objects you can use, provides tips for designing providers so that they can be tested, and lists provider-specific features you should test.
  • Service Testing focuses on testing services. It also lists service-specific features you should test.
  • What to Test is an overview of the types of testing you should do. It focuses on testing system-wide aspects of Android that can affect every component in your application.

Procedures

Tutorials

  • The Hello, Testing tutorial introduces basic testing concepts and procedures.
  • For a more advanced tutorial, try Activity Testing, which guides you through a more complex testing scenario.

Tools

  • The UI/Application Exerciser Monkey, usually called Monkey, is a command-line tool that sends pseudo-random streams of keystrokes, touches, and gestures to a device.
  • The monkeyrunner tool is an API and execution environment. You use monkeyrunner with Python programs to test applications and devices.

Android Search

Search is a core user feature on Android. Users should be able to search any data that is available to them, whether the content is located on the device or the Internet. To help create a consistent search experience for users, Android provides a search framework that helps you implement search for your application.
Figure 1. Screenshot of a search dialog with custom search suggestions.
The search framework offers two modes of search input: a search dialog at the top of the screen or a search widget (SearchView) that you can embed in your activity layout. In either case, the Android system will assist your search implementation by delivering search queries to a specific activity that performs searchs. You can also enable either the search dialog or widget to provide search suggestions as the user types. Figure 1 shows an example of the search dialog with optional search suggestions.
Once you've set up either the search dialog or the search widget, you can:
  • Enable voice search
  • Provide search suggestions based on recent user queries
  • Provide custom search suggestions that match actual results in your application data
  • Offer your application's search suggestions in the system-wide Quick Search Box
Note: The search framework does not provide APIs to search your data. To perform a search, you need to use APIs appropriate for your data. For example, if your data is stored in an SQLite database, you should use the android.database.sqlite APIs to perform searches.

Also, there is no guarantee that every device provides a dedicated SEARCH button to invoke the search interface in your application. When using the search dialog or a custom interface, you must always provide a search button in your UI that activates the search interface. For more information, see Invoking the search dialog.
The following documents show you how to use Android's framework to implement search:
Creating a Search Interface
How to set up your application to use the search dialog or search widget.
Adding Recent Query Suggestions
How to provide suggestions based on queries previously used.
Adding Custom Suggestions
How to provide suggestions based on custom data from your application and also offer them in the system-wide Quick Search Box.
Searchable Configuration
A reference document for the searchable configuration file (though the other documents also discuss the configuration file in terms of specific behaviors).

Protecting User Privacy

When you implement search in your application, take steps to protect the user's privacy. Many users consider their activities on the phone—including searches—to be private information. To protect each user's privacy, you should abide by the following principles:
  • Don't send personal information to servers, but if you must, do not log it.
    Personal information is any information that can personally identify your users, such as their names, email addresses, billing information, or other data that can be reasonably linked to such information. If your application implements search with the assistance of a server, avoid sending personal information along with the search queries. For example, if you are searching for businesses near a zip code, you don't need to send the user ID as well; send only the zip code to the server. If you must send the personal information, you should not log it. If you must log it, protect that data very carefully and erase it as soon as possible.
  • Provide users with a way to clear their search history.
    The search framework helps your application provide context-specific suggestions while the user types. Sometimes these suggestions are based on previous searches or other actions taken by the user in an earlier session. A user might not wish for previous searches to be revealed to other device users, for instance, if the user shares the device with a friend. If your application provides suggestions that can reveal previous search activities, you should implement the ability for the user to clear the search history. If you are using SearchRecentSuggestions, you can simply call theclearHistory() method. If you are implementing custom suggestions, you'll need to provide a similar "clear history" method in your content provider that the user can execute.

Android USB Host and Accessory

Android supports a variety of USB peripherals and Android USB accessories (hardware that implements the Android accessory protocol) through two modes: USB accessory and USB host. In USB accessory mode, the external USB hardware act as the USB hosts. Examples of accessories might include robotics controllers; docking stations; diagnostic and musical equipment; kiosks; card readers; and much more. This gives Android-powered devices that do not have host capabilities the ability to interact with USB hardware. Android USB accessories must be designed to work with Android-powered devices and must adhere to the Android accessory communication protocol. In USB host mode, the Android-powered device acts as the host. Examples of devices include digital cameras, keyboards, mice, and game controllers. USB devices that are designed for a wide range of applications and environments can still interact with Android applications that can correctly communicate with the device.
Figure 1 shows the differences between the two modes. When the Android-powered device is in host mode, it acts as the USB host and powers the bus. When the Android-powered device is in USB accessory mode, the connected USB hardware (an Android USB accessory in this case) acts as the host and powers the bus.
Figure 1. USB Host and Accessory Modes
USB accessory and host modes are directly supported in Android 3.1 (API level 12) or newer platforms. USB accessory mode is also backported to Android 2.3.4 (API level 10) as an add-on library to support a broader range of devices. Device manufacturers can choose whether or not to include the add-on library on the device's system image.
Note: Support for USB host and accessory modes are ultimately dependant on the device's hardware, regardless of platform level. You can filter for devices that support USB host and accessory through a <uses-feature> element. See the USB accessory and host documentation for more details.

Debugging considerations

When debugging applications that use USB accessory or host features, you most likely will have USB hardware connected to your Android-powered device. This will prevent you from having an adb connection to the Android-powered device via USB. You can still access adb over a network connection. To enable adb over a network connection:
  1. Connect the Android-powered device via USB to your computer.
  2. From your SDK platform-tools/ directory, enter adb tcpip 5555 at the command prompt.
  3. Enter adb connect <device-ip-address>:5555 You should now be connected to the Android-powered device and can issue the usual adb commands like adb logcat.
  4. To set your device to listen on USB, enter adb usb.

Android Near Field Communication

Near Field Communication (NFC) is a set of short-range wireless technologies, typically requiring a distance of 4cm or less to initiate a connection. NFC allows you to share small payloads of data between an NFC tag and an Android-powered device, or between two Android-powered devices.
Tags can range in complexity. Simple tags offer just read and write semantics, sometimes with one-time-programmable areas to make the card read-only. More complex tags offer math operations, and have cryptographic hardware to authenticate access to a sector. The most sophisticated tags contain operating environments, allowing complex interactions with code executing on the tag. The data stored in the tag can also be written in a variety of formats, but many of the Android framework APIs are based around a NFC Forum standard called NDEF (NFC Data Exchange Format).
NFC Basics
This document describes how Android handles discovered NFC tags and how it notifies applications of data that is relevant to the application. It also goes over how to work with the NDEF data in your applications and gives an overview of the framework APIs that support the basic NFC feature set of Android.
Advanced NFC
This document goes over the APIs that enable use of the various tag technologies that Android supports. When you are not working with NDEF data, or when you are working with NDEF data that Android cannot fully understand, you have to manually read or write to the tag in raw bytes using your own protocol stack. In these cases, Android provides support to detect certain tag technologies and to open communication with the tag using your own protocol stack.

Android Location and Maps

Location and maps-based applications are compelling for mobile device users. You can build these capabilities into your applications using the classes of the android.locationpackage and the Google Maps external library. The sections below provide details.

Location Services

Android gives your applications access to the location services supported by the device through the classes in theandroid.location package. The central component of the location framework is the LocationManager system service, which provides APIs to determine location and bearing of the underlying device (if available).
As with other system services, you do not instantiate a LocationManager directly. Rather, you request an instance from the system by calling getSystemService(Context.LOCATION_SERVICE). The method returns a handle to a newLocationManager instance.
Once your application has a LocationManager, your application is able to do three things:
  • Query for the list of all LocationProviders for the last known user location.
  • Register/unregister for periodic updates of the user's current location from a location provider (specified either by criteria or name).
  • Register/unregister for a given Intent to be fired if the device comes within a given proximity (specified by radius in meters) of a given lat/long.
For more information, read the guide to Obtaining User Location.

Google Maps External Library

To make it easier for you to add powerful mapping capabilities to your application, Google provides a Maps external library that includes the com.google.android.maps package. The classes of the com.google.android.maps package offer built-in downloading, rendering, and caching of Maps tiles, as well as a variety of display options and controls.
The key class in the Maps package is com.google.android.maps.MapView, a subclass of ViewGroup. A MapView displays a map with data obtained from the Google Maps service. When the MapView has focus, it will capture keypresses and touch gestures to pan and zoom the map automatically, including handling network requests for additional maps tiles. It also provides all of the UI elements necessary for users to control the map. Your application can also use MapView class methods to control the MapView programmatically and draw a number of Overlay types on top of the map.
In general, the MapView class provides a wrapper around the Google Maps API that lets your application manipulate Google Maps data through class methods, and it lets you work with Maps data as you would other types of Views.
The Maps external library is not part of the standard Android library, so it may not be present on some compliant Android-powered devices. Similarly, the Maps external library is not included in the standard Android library provided in the SDK. So that you can develop using the classes of the com.google.android.maps package, the Maps external library is made available to you as part of the Google APIs add-on for the Android SDK.
To learn more about the Maps external library and how to download and use the Google APIs add-on, visit
For your convenience, the Google APIs add-on is also available as a downloadable component from the Android SDK and AVD Manager (see Adding SDK Components).
Note: In order to display Google Maps data in a MapView, you must register with the Google Maps service and obtain a Maps API Key. For information about how to get a Maps API Key, see Obtaining a Maps API Key.

Android Multimedia and Camera

The Android multimedia framework includes support for capturing and playing audio, video and images in a variety of common media types, so that you can easily integrate them into your applications. You can play audio or video from media files stored in your application's resources, from standalone files in the file system, or from a data stream arriving over a network connection, all using the MediaPlayer or JetPlayer APIs. You can also record audio, video and take pictures using the MediaRecorderand Camera APIs if supported by the device hardware.
The following topics show you how to use the Android framework to implement multimedia capture and playback.
MediaPlayer
How to play audio and video in your application.
JetPlayer
How to play interactive audio and video in your application using content created with JetCreator.
Camera
How to use a device camera to take pictures or video in your application.
Audio Capture
How to record sound in your application.