giovedì 5 febbraio 2015

Security Requirements

http://sqgne.org/presentations/2007-08/Hope-Sep-2007.pdf

martedì 13 gennaio 2015

http://developer.android.com/distribute/tools/launch-checklist.html

Launch Checklist

Before you publish your apps on Google Play and distribute them to users, you need to get the apps ready, test them, and prepare your promotional materials.
This page helps you understand the publishing process and get ready for a successful product launch on Google Play. It summarizes some of the tasks you'll need to complete before publishing your app on Google Play, such as creating a signed, release-ready application package (APK), understanding the requirements of the app, and creating the product page and graphic assets for each of your apps.
The preparation and publishing tasks are numbered to give you a rough idea of sequence. However, you can handle the tasks in any sequence that works for you or you can skip steps as appropriate.
As you move toward publishing, a variety of support resources are available to you. Relevant links are provided in each step.

1. Understand the Publishing Process


Before you begin the steps in this checklist, you should take a moment to read and understand the overall publishing workflow and become familiar with how the process works. In particular, you or your development team will need to prepare your apps for release using a process common to all Android apps. The Publishing workflow documents provide the details on how publishing works and how to get an APK ready for release.
Once you are familiar with publishing in general, continue reading to understand the issues that you should consider when publishing apps on Google Play.

Related resources

2. Understand Google Play Policies and Agreements


Make sure that you understand and follow the Google Play program policies that you accepted when registering. Google Play actively enforces the policies and any violations can lead to suspension of your apps or, for repeated violations, termination of your developer account.

Related resources

3. Test for Quality


Before you publish apps on Google Play, it's important to make sure that they meet the basic quality expectations for all Android apps, on all of the devices that you are targeting. You can check your app's quality by setting up a test environment and testing the app against a short set of quality criteria that applies to all apps. For complete information, see the Core App Quality guidelines.
If your app is targeting tablet devices, make sure that it delivers a rich, compelling experience to your tablet customers. See the Tablet App Quality guidelines for recommendations on ways to optimize your app for tablets.
If you plan to make your apps available to Google Play for Education, then you need to make sure they are suitable for a K-12 classroom and offer outstanding educational value. See the Education Guidelines for information on the characteristics your education apps should exhibit.

Related resources

4. Determine your App’s Content Rating


Google Play requires you to set a content rating for your app, which informs Google Play users of its maturity level. Before you publish, you should confirm what rating level you want to use. The available content rating levels are:
  • Everyone
  • Low maturity
  • Medium maturity
  • High maturity
On their Android devices, Android users can set the desired maturity level for browsing. Google Play then filters apps based on the setting, so the content rating you select can affect the app's distribution to users. You can assign (or change) the content rating for your apps in the Developer Console, no changes are required in your app binary.

Related resources

5. Determine Country Distribution


Google Play lets you control what countries and territories your apps are distributed to. For the widest reach and the largest potential customer base, you’d normally want to distribute to all available countries and territories. However, because of business needs, app requirements, or launch dependencies, you might want to exclude one or more countries from your distribution.
It's important to determine the exact country distribution early, because it can affect:
  • The need for localized resources in the app.
  • The need for a localized app description in the Developer Console.
  • Legal requirements for the app that may be specific to certain countries.
  • Time zone support, local pricing, and so on.
With your target countries in mind, you should assess your localization needs, both in your apps and in their Google Play listings details, and start the work of localization well in advance of your target launch date.
See Localization Checklist for key steps and considerations in the localization process.

Related resources

6. Confirm the App's Overall Size


The overall size of your app can affect its design and how you publish it on Google Play. Currently, the maximum size for an APK published on Google Play is 50 MB. If your app exceeds that size, or if you want to offer a secondary download, you can use APK Expansion Files, which Google Play will host for free on its server infrastructure and automatically handle the download to devices.
  • The maximum size for an APK published on Google Play is 50 MB.
  • You can use up to two (2) APK Expansion Files, each up to 2GB in size, for each APK.
Using APK Expansion files is a convenient, cost-effective method of distributing large apps. However, the use of APK Expansion Files requires some changes in your app binary, so you will need to make those changes before creating your release-ready APK.
To minimize the size of your app binary, make sure that you run the Proguard tool or similar obfuscator on your code when building your release-ready APK.

Related resources

7. Confirm the App's Platform and Screen Compatibility Ranges


Before publishing, it's important to make sure that your apps are designed to run properly on the Android platform versions and device screen sizes that you want to target.
From an app-compatibility perspective, Android platform versions are defined by API level. You should confirm the minimum version that your app is compatible with <minSdkVersion>, as that will affect its distribution to Android devices once it is published.
For screen sizes, you should confirm that the app runs properly and looks good on the range of screen sizes and pixel densities that you want to support. You should follow the advice provided in Supporting Multiple Screens to provide scalable support for multiple screen sizes. However, if you have been unable to do so, declare the minimum screen-size supported by your apps using <supports-screens>. Google Play will then restrict the availability of your apps accordingly, making them available to devices with the declared screen size or large.
To get a better understanding of the current device penetration of Android platform versions and screen sizes across all Android devices, see the Device Dashboard charts.

Related resources

8. Decide Whether your App will be Free or Priced


On Google Play, you can publish apps as free to download or priced. Free apps can be downloaded by any Android user in Google Play. Paid apps can be downloaded only by users who are in a country that supports paid downloads and have registered a form of payment in Google Play, such as a credit card or Direct Carrier Billing.
Deciding whether you apps will be free or paid is important because, on Google Play, free apps must remain free.
  • Once you publish an app as a free app, you cannot change it to being a priced app. However, you can still sell in-app products and subscriptions through Google Play's In-app Billing service.
  • If you publish your app as a priced app, you can change it at any time to be a free app (but cannot then change it back to priced). You can also sell in-app products and subscriptions.
If your app is be priced, or if you'll be selling in-app products, you need set up a Google Wallet Merchant Account before you can publish.

Related resources

9. Consider using In-app Billing


Google Play In-app Billing lets you sell digital content in your applications. You can use the service to sell a wide range of content, including downloadable content such as media files or photos, and virtual content such as game levels or potions. In-app Billing service lets you sell one-time purchases and subscriptions from inside your app. This can help you to monetize the app over its installed lifetime.
If your are looking for more ways to monetize your app and build engagement, you should consider In-app Billing or Instant Buy. These services have become very popular with both users and developers. To use In-app Billing or Instant Buy, you need to make changes to your app binary, so you will need to complete and test your implementation before creating your release-ready APK.

Related resources

10. Set Prices for your Products


If your apps is priced or you’ll sell in-app or physical products, Google Play lets you set prices for your products in a variety of currencies, for users in markets around the world. You can set prices individually in different currencies, so you have the flexibility to adjust your price according to market conditions and exchange rates.
Before you publish, consider how you’ll price your products and what your prices will be in various currencies. Later, you can set prices in all available currencies through the Developer Console.

Related resources

11. Start Localization


With your country targeting in mind, it's a good idea to assess your localization needs, ensure your apps are internationalized, and start the work of localizing well in advance of your target launch date.
In addition to your application design, there are at least three aspects of localization to consider:
  • Localizing the strings, images, and other resources in your apps.
  • Localizing your apps’ store listing details on Google Play.
  • Localizing the apps’ graphic assets, screenshots, and videos that accompany your store listing.
See Localization Checklist for key steps and considerations in the localization process.
To localize your store listing, first create and finalize your app title, description, and promotional text. Collect and send all of these for localization. You can optionally translate the "Recent Changes" text for app updates as well. Later you can add your localized listing details in the Developer Console, or you can choose to let Google Play auto-translate your listing details into the languages you support.
A key part of making your app listing attractive to a global customer base is creating localized versions of your promotional graphics, screenshots and videos. For example, your app's feature graphic might include text that should be translated, for maximum effectiveness. You can create different versions of your promotional graphics for each language and upload them to the Developer Console. If you offer a promotional video, you can create localized versions of it and then add a link to the correct localized video for each language you support.
When your translations are complete, move them into your app resources as needed and test that they are loaded properly. Save your app's translated listing details for later, when you upload assets and configure the store listing.

Related resources

12. Prepare Promotional Graphics, Screenshots, and Videos


When you publish on Google Play, you can supply a variety of high-quality graphic assets to showcase your app or brand. After you publish, these appear on your store listing page, search results, and elsewhere. These graphic assets are key parts of a successful store listing page that attracts and engages users, so you should consider having a professional produce them for you. Screenshots and videos are also very important, because they show how your apps look, how they’re used or played, and what makes them different.
All of your graphic assets should be designed so that they are easy to see and highlight your apps or brand in a colorful, interesting way. The assets should reference the same logo and icon as users will find in the All Apps launcher once they have downloaded the app. Your graphic assets should also fit in well with the graphic assets of all the apps you publish, which will be also be displayed to users on your store listing page.
To help you market your apps more effectively to a global audience, Google Play lets you create localized versions of your promotional graphics, screenshots, and videos and upload them to the Developer Console. When a user visits your app's store listing, Google Play displays the promotional graphic, screenshots, and video that you've provided for the user's language.
To localize your promotional graphics, you can translate any embedded text, use different imagery or presentation, or change your marketing approach to best address the needs of users in specific languages. For example, if your feature or promotional graphic includes an embedded product name or tag line, you can translate that text and add it to a localized version of the promotional graphic.
Because your localized graphic assets and videos are so important, you should get started on creating and localizing them well in advance of your target publishing date.

Related resources

13. Build and Upload the Release-ready APK


When you are satisfied that your apps meet your UI, compatibility, and quality requirements, you can build the release-ready versions of the apps. You upload the release-ready APKs to your Developer Console and distribute to users.
The process for preparing a release-ready APK is the same for all apps, regardless of how they are distributed. Generally the process includes basic code cleanup and optimization, building and signing with your release key, and final testing.
For complete details on how to create a release-ready version of your app, read Preparing for Release.
Once you have the release-ready APKs in hand, you can upload them to the Developer Console. If necessary, you can replace an APK with a more recent version before publishing.

14. Plan a Beta Release


Before launching your apps, it's always valuable to get real-world feedback from users — even more so when you are launching new apps. It's highly recommended that you distribute a pre-release version of your app to users across your key markets and provide an easy means for them to provide feedback and report bugs.
Google Play can help you set up a beta program for your app. After you sign in to your Developer Console and have upload your APKs, you can set up groups of users for alpha and beta testing the apps. You can start with a small group of alpha testers, then move to a larger group of beta testers. Once users are added, they access your app's store listing and install the app. Users on alpha or beta versions cannot leave reviews or ratings, so there is no risk to your rating on Google Play. You need to arrange a mechanism for any testing feedback to be delivered - such as a Google Forum or Google+.
The feedback you receive will help you adjust your UI, translations, and store listing to ensure a great experience for users.

15. Complete the Apps’ Store Listing


On Google Play, your apps’ product information is shown to users on their store listing pages, the pages that users visit to learn more about your apps and the pages from which they will decide to purchase or download your apps, on their Android devices or on the web.
Google Play gives you a variety of ways to promote your apps and engage with users on your store listing pages, from colorful graphics, screenshots, and videos to localized descriptions, release details, and links to your other apps. As you prepare to publish your apps, make sure that you take advantage of all that your product detail pages can offer, making your apps as compelling as possible to users.
You should begin planning your product pages in advance of your target launch date, arranging for localized description, high-quality graphic assets, screenshots and video, and so on.
As you get near your target publishing date, you should become familiar with all the fields, options, and assets associated with the store listing configuration page in the Developer Console. As you collect the information and assets for the page, make sure that you can enter or upload it to the Developer Console, until the page is complete and ready for publishing.
After you've set your apps’ geographic targeting in the Developer Console, remember to add your localized store listing, promotional graphics, and so on, for all of the languages that you support.
If your app is targeting tablet devices, make sure to include at least one screenshot of the app running on a tablet, and highlight your apps’ support for tablets in the app description, release notes, promotional campaigns, and elsewhere.

Related resources

16. Use Google Play Badges and Links in your Promotional Campaigns


Google Play badges give you an officially branded way of promoting your apps to Android users. Use the Google Play Badge generator to quickly create badges to link users to your products from web pages, ads, reviews, and more. You can also use special link formats to link directly to your store listing page, to a list of your products, or to search results.
To help your apps get traction after launch, it's strongly recommended that you support launch with a promotional campaign that announces your product through many channels as possible, in as many countries as possible. For example, you can promote a launch using ad placements, social network or blog posts, video and other media, interviews and reviews, or any other channels available.

Related resources

17. Final Checks and Publishing


When you think you’re ready to publish, sign in to the Developer Console and take a few moments for a few final checks.
Make sure that:
  • Your developer profile has the correct information and is linked to the proper Google Wallet merchant account (if you’re selling products).
  • You have the right version of the apps uploaded.
  • All parts of your store listing are ready, including all graphic assets, screenshots, video, localized descriptions, and so on.
  • You have set your app's pricing to free or priced.
  • You have set country (and carrier) targeting and priced your products (if appropriate) in buyer currencies
  • "Compatible devices" shows that your apps are reaching the devices that you’re targeting. If not, you should check with your development team on the apps’ requirements and filtering rules.
  • You’ve provided the correct link to your website and the correct support email address.
  • Your apps don’t violate content policy guidelines.
  • You’ve acknowledged that your apps meets the guidelines for Android content on Google Play and also US export laws.
Your apps are now ready to publish!
If you’re releasing an update, make sure to read the requirements for publishing updates.
When you’re ready, click the Publish button in the Developer Console. Within a few hours, your apps will become available to users and your product page will appear in Google Play for browsing, searching, or linking from your promotional campaigns.

Related resources

18. Support Users after Launch


After you publish apps or app updates, it's crucial for you to support your customers. Prompt and courteous support can provide a better experience for users that results in better ratings and more positive reviews for your products. Users are likely to be more engaged with your app and recommend it if you’re responsive to their needs and feedback. This is especially true after publishing if you’re using a coordinated promotional campaign.
There are a number of ways that you can keep in touch with users and offer them support. The most fundamental is to provide your support email address on your store listing pages. Beyond that, you can provide support in any way you choose, such as a forum, mailing list, or a Google+ page. The Google Play team provides user support for downloading, installing. and payments issues, but issues that fall outside of these topics will be in your domain. Examples of issues you can support include: feature requests, questions about using the apps, and questions about compatibility settings.
After publishing, plan to:
  • Check your ratings and reviews frequently on your apps’ store listing pages. Watch for recurring themes that could signal bugs or other issues.
  • Be mindful of new Android platform version launches, as compatibility settings for your apps might need to be updated.
  • Put a link to your support resources on your website and set up any other support such as forums.
  • Provide an appropriate support email address on your store listing pages and respond to users when they take the time to email you.
  • Beyond the automatic refund window offered by Google Play, be generous with your own refund policy, as satisfied users will be more likely to purchase in the future.
  • Acknowledge and fix issues in your apps. It helps to be transparent and list known issues on your store listing pages proactively.
  • Publish updates as frequently as you’re able, without sacrificing quality or annoying users with too-frequent updates.
  • With each update, make sure to provide a summary of what's changed. You can enter this information in the Developer Console. Users will read it and appreciate that you are serious about improving the quality of your apps.

Related resources

lunedì 12 gennaio 2015

How can I get crash data (stack traces at least) from my Android application?


http://stackoverflow.com/questions/601503/how-do-i-obtain-crash-data-from-my-android-application


How can I get crash data (stack traces at least) from my Android application? At least when working on my own device being retrieved by cable, but ideally from any instance of my application running on the wild so that I can improve it and make it more solid.

You might try the ACRA (Application Crash Report for Android) library:
ACRA is a library enabling Android Application to automatically post their crash reports to a GoogleDoc form. It is targetted to android applications developers to help them get data from their applications when they crash or behave erroneously.

http://www.acra.ch/

https://cloudant.com/product/pricing/ 
http://developer.android.com/tools/testing/testing_ui.html

UI Testing

In addition to unit testing the individual components that make up your Android application (such as activities, services, and content providers), it is also important that you test the behavior of your application’s user interface (UI) when it is running on a device. UI testing ensures that your application returns the correct UI output in response to a sequence of user actions on a device, such as entering keyboard input or pressing toolbars, menus, dialogs, images, and other UI controls.
Functional or black-box UI testing does not require testers to know the internal implementation details of the app, only its expected output when a user performs a specific action or enters a specific input. This approach allows for better separation of development and testing roles in your organization.
One common approach to UI testing is to run tests manually and verify that the app is behaving as expected. However, this approach can be time-consuming, tedious, and error-prone. A more efficient and reliable approach is to automate the UI testing with a software testing framework. Automated testing involves creating programs to perform testing tasks (test cases) to cover specific usage scenarios, and then using the testing framework to run the test cases automatically and in a repeatable manner.

Overview


The Android SDK provides the following tools to support automated, functional UI testing on your application:
  • uiautomatorviewer - A GUI tool to scan and analyze the UI components of an Android application.
  • uiautomator - A Java library containing APIs to create customized functional UI tests, and an execution engine to automate and run the tests.
To use these tools, you must have the following versions of the Android development tools installed:
  • Android SDK Tools, Revision 21 or higher
  • Android SDK Platform, API 16 or higher

Workflow for the the uiautomator testing framework

Here's a short overview of the steps required to automate UI testing:
  1. Prepare to test by installing the app on a test device, analyzing the app’s UI components, and ensuring that your application is accessible by the test automation framework.
  2. Create automated tests to simulate specific user interactions on your application.
  3. Compile your test cases into a JAR file and install it on your test device along with your app.
  4. Run the tests and view the test results.
  5. Correct any bugs or defects discovered in testing.

Analyzing Your Application's UI


Before you start writing your test cases, it's helpful to familiarize yourself with the UI components (including the views and controls) of the targeted application. You can use the uiautomatorviewer tool to take a snapshot of the foreground UI screen on any Android device that is connected to your development machine. The uiautomatorviewer tool provides a convenient visual interface to inspect the layout hierarchy and view the properties of the individual UI components that are displayed on the test device. Using this information, you can later create uiautomator tests with selector objects that target specific UI components to test.
User interface of uiautomatorviewer tool
Figure 1. The uiautomatorviewer showing the captured interface of a test device.
To analyze the UI components of the application that you want to test:
  1. Connect your Android device to your development machine.
  2. Open a terminal window and navigate to <android-sdk>/tools/.
  3. Run the tool with this command:
    $ uiautomatorviewer
  4. To capture a screen for analysis, click the Device Screenshot button in the GUI of the uiautomatorviewer tool.
    Note: If you have more than one device connected, specify the device for screen capture by setting theANDROID_SERIAL environment variable:
    1. Find the serial numbers for your connected devices by running this command:
      $ adb devices
    2. Set the ANDROID_SERIAL environment variable to select the device to test:
      • In Windows:
        set ANDROID_SERIAL=<device serial number>
      • In UNIX:
        export ANDROID_SERIAL=<device serial number>
    If you are connected to only a single device, you do not need to set the ANDROID_SERIAL environment variable.
  5. View the UI properties for your application:
    • Hover over the snapshot in the left-hand panel to see the UI components identified by the uiautomatorviewer tool. You can view the component’s properties listed in the lower right-hand panel, and the layout hierarchy in the upper right-hand panel.
    • Optionally, click on the Toggle NAF Nodes button to see UI components that are not accessible to the uiautomatortesting framework. Only limited information may be available for these components.

Preparing to Test


Before using the uiautomator testing framework, complete these pre-flight tasks:

Load the application to a device

If you are reading this document, chances are that the Android application that you want to test has not been published yet. If you have a copy of the APK file, you can install the APK onto a test device by using the adb tool. To learn how to install an APK file using the adb tool, see the adb documentation.

Identify the application’s UI components

Before writing your uiautomator tests, first identify the UI components in the application that you want to test. Typically, good candidates for testing are UI components that are visible and that users can interact with. The UI components should also have visible text labels, android:contentDescription values, or both.
You can inspect the visible screen objects in an application conveniently by using the uiautomatorviewer tool. For more information about how to analyze an application screen with this tool, see the section Analyzing Your Application’s UI. For more information about the common types of UI components provided by Android, see User Interface.

Ensure that the application is accessible

This step is required because the uiautomator tool depends on the accessibility features of the Android framework to execute your functional UI tests. You should include these minimum optimizations to support the uiautomator tool:
  • Use the android:contentDescription attribute to label the ImageButtonImageViewCheckBox and other user interface controls.
  • Provide an android:hint attribute instead of a content description for EditText fields
  • Associate an android:hint attribute with any graphical icons used by controls that provide feedback to the user (for example, status or state information).
  • Make sure that all the user interface elements are accessible with a directional controller, such as a trackball or D-pad.
  • Use the uiautomatorviewer tool to ensure that the UI component is accessible to the testing framework. You can also test the application by turning on accessibility services like TalkBack and Explore by Touch, and try using your application using only directional controls.
For more information about implementing and testing accessibility, see Making Applications Accessible.
Note: To identify the non-accessible components in the UI, click on the Toggle NAF Nodes option in theuiautomatorviewer tool.
Generally, Android application developers get accessibility support for free, courtesy of the View and ViewGroup classes. However, some applications use custom view components to provide a richer user experience. Such custom components won't get the accessibility support that is provided by the standard Android UI components. If this applies to your application, ensure that the application developer exposes the custom drawn UI components to Android accessibility services, by implementing the AccessibilityNodeProvider class. For more information about making custom view components accessible, see Making Applications Accessible.

Configure your development environment

If you're developing in Eclipse, the Android SDK provides additional tools that help you write test cases usinguiautomator and buiild your JAR file. In order to set up Eclipse to assist you, you need to create a project that includes the uiautomator client library, along with the Android SDK library. To configure Eclipse:
  1. Create a new Java project in Eclipse, and give your project a name that is relevant to the tests you’re about to create (for example, "MyAppNameTests"). In the project, you will create the test cases that are specific to the application that you want to test.
  2. From the Project Explorer, right-click on the new project that you created, then select Properties > Java Build Path, and do the following:
    1. Click Add Library > JUnit then select JUnit3 to add JUnit support.
    2. Click Add External JARs... and navigate to the SDK directory. Under the platforms directory, select the latest SDK version and add both the uiautomator.jar and android.jar files.
If you did not configure Eclipse as your development environment, make sure that the uiautomator.jar and android.jarfiles from the <android-sdk>/platforms/<sdk> directory are in your Java class path.
Once you have completed these prerequisite tasks, you're almost ready to start creating your uiautomator tests.

Creating uiautomator Tests


To build a test that runs in the uiautomator framework, create a test case that extends the UiAutomatorTestCase class. In Eclipse, the test case file goes under the src directory in your project. Later, you will build the test case as a JAR file, then copy this file to the test device. The test JAR file is not an APK file and resides separately from the application that you want to test on the device.
Because the UiAutomatorTestCase class extends junit.framework.TestCase, you can use the JUnit Assert class to test that UI components in the app return the expected results. To learn more about JUnit, you can read the documentation on the junit.org home page.
The first thing your test case should do is access the device that contains the target app. It’s also good practice to start the test from the Home screen of the device. From the Home screen (or some other starting location you’ve chosen in the target app), you can use the classes provided by the uiautomator API to simulate user actions and to test specific UI components. For an example of how to put together a uiautomator test case, see the sample test case.

uiautomator API

The uiautomator API is bundled in the uiautomator.jar file under the <android-sdk>/platforms/ directory. The API includes these key classes that allow you to capture and manipulate UI components on the target app:
UiDevice
Represents the device state. In your tests, you can call methods on the UiDevice instance to check for the state of various properties, such as current orientation or display size. Your tests also can use the UiDevice instance to perform device level actions, such as forcing the device into a specific rotation, pressing the d-pad hardware button, or pressing the Home and Menu buttons.
To get an instance of UiDevice and simulate a Home button press:
getUiDevice().pressHome();
UiSelector
Represents a search criteria to query and get a handle on specific elements in the currently displayed UI. If more than one matching element is found, the first matching element in the layout hierarchy is returned as the targetUiObject. When constructing a UiSelector, you can chain together multiple properties to refine your search. If no matching UI element is found, a UiAutomatorObjectNotFoundException is thrown. You can use the childSelector()method to nest multiple UiSelector instances. For example, the following code example shows how to specify a search to find the first ListView in the currently displayed UI, then search within that ListView to find a UI element with the text property Apps.
UiObject appItem = new UiObject(new UiSelector()
   .className("android.widget.ListView").instance(1)
   .childSelector(new UiSelector().text("Apps")));
UiObject
Represents a UI element. To create a UiObject instance, use a UiSelector that describes how to search for, or select, the UI element.
The following code example shows how to construct UiObject instances that represent a Cancel button and a OKbutton in your application.
UiObject cancelButton = new UiObject(new UiSelector().text("Cancel"));
UiObject okButton = new UiObject(new UiSelector().text("OK"));
You can reuse the UiObject instances that you have created in other parts of your app testing, as needed. Note that the uiautomator test framework searches the current display for a match every time your test uses a UiObjectinstance to click on a UI element or query a property.
In the following code example, the uiautomator test framework searches for a UI element with the text property OK. If a match is found and if the element is enabled, the framework simulates a user click action on the element.
if(okButton.exists() && okButton.isEnabled()) {
  okButton.click();
}
You can also restrict the search to find only elements of a specific class. For example, to find matches of the Buttonclass:
UiObject cancelButton = new UiObject(new UiSelector().text("Cancel")
   .className("android.widget.Button"));
UiObject okButton = new UiObject(new UiSelector().text("OK")
   .className("android.widget.Button"));
UiCollection
Represents a collection of items, for example songs in a music album or a list of emails in an inbox. Similar to aUiObject, you construct a UiCollection instance by specifying a UiSelector. The UiSelector for a UiCollectionshould search for a UI element that is a container or wrapper of other child UI elements (such as a layout view that contains child UI elements). For example, the following code snippet shows how to construct a UiCollection to represent a video album that is displayed within a FrameLayout:
UiCollection videos = new UiCollection(new UiSelector()
   .className("android.widget.FrameLayout"));
If the videos are listed within a LinearLayout view, and you want to to retrieve the number of videos in this collection:
int count = videos.getChildCount(new UiSelector()
   .className("android.widget.LinearLayout"));
If you want to find a specific video that is labeled with the text element Cute Baby Laughing from the collection and simulate a user-click on the video:
UiObject video = videos.getChildByText(new UiSelector()
   .className("android.widget.LinearLayout"), "Cute Baby Laughing");
video.click();
Similarly, you can simulate other user actions on the UI object. For example, if you want to simulate selecting a checkbox that is associated with the video:
UiObject checkBox = video.getChild(new UiSelector()
   .className("android.widget.Checkbox"));
if(!checkBox.isSelected()) checkbox.click();
UiScrollable
Represents a scrollable collection of UI elements. You can use the UiScrollable class to simulate vertical or horizontal scrolling across a display. This technique is helpful when a UI element is positioned off-screen and you need to scroll to bring it into view.
For example, the following code shows how to simulate scrolling down the Settings menu and clicking on an About tablet option:
UiScrollable settingsItem = new UiScrollable(new UiSelector()
   .className("android.widget.ListView"));
UiObject about = settingsItem.getChildByText(new UiSelector()
   .className("android.widget.LinearLayout"), "About  tablet");
about.click()
For more information about these APIs, see the uiautomator reference.

A sample uiautomator test case

The following code example shows a simple test case which simulates a user bringing up the Settings app in a stock Android device. The test case mimics all the steps that a user would typically take to perform this task, including opening the Home screen, launching the All Apps screen, scrolling to the Settings app icon, and clicking on the icon to enter the Settings app.
package com.uia.example.my;
// Import the uiautomator libraries
import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiObjectNotFoundException;
import com.android.uiautomator.core.UiScrollable;
import com.android.uiautomator.core.UiSelector;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
public class LaunchSettings extends UiAutomatorTestCase {   

   public void testDemo() throws UiObjectNotFoundException {   
      
      // Simulate a short press on the HOME button.
      getUiDevice().pressHome();
      
      // We’re now in the home screen. Next, we want to simulate 
      // a user bringing up the All Apps screen.
      // If you use the uiautomatorviewer tool to capture a snapshot 
      // of the Home screen, notice that the All Apps button’s 
      // content-description property has the value “Apps”.  We can 
      // use this property to create a UiSelector to find the button. 
      UiObject allAppsButton = new UiObject(new UiSelector()
         .description("Apps"));
      
      // Simulate a click to bring up the All Apps screen.
      allAppsButton.clickAndWaitForNewWindow();
      
      // In the All Apps screen, the Settings app is located in 
      // the Apps tab. To simulate the user bringing up the Apps tab,
      // we create a UiSelector to find a tab with the text 
      // label “Apps”.
      UiObject appsTab = new UiObject(new UiSelector()
         .text("Apps"));
      
      // Simulate a click to enter the Apps tab.
      appsTab.click();

      // Next, in the apps tabs, we can simulate a user swiping until
      // they come to the Settings app icon.  Since the container view 
      // is scrollable, we can use a UiScrollable object.
      UiScrollable appViews = new UiScrollable(new UiSelector()
         .scrollable(true));
      
      // Set the swiping mode to horizontal (the default is vertical)
      appViews.setAsHorizontalList();
      
      // Create a UiSelector to find the Settings app and simulate      
      // a user click to launch the app. 
      UiObject settingsApp = appViews.getChildByText(new UiSelector()
         .className(android.widget.TextView.class.getName()), 
         "Settings");
      settingsApp.clickAndWaitForNewWindow();
      
      // Validate that the package name is the expected one
      UiObject settingsValidation = new UiObject(new UiSelector()
         .packageName("com.android.settings"));
      assertTrue("Unable to detect Settings", 
         settingsValidation.exists());   
  }   }

Building and Deploying Your uiautomator Tests


Once you have coded your test, follow these steps to build and deploy your test JAR to your target Android test device:
  1. Create the required build configuration files to build the output JAR. To generate the build configuration files, open a terminal and run the following command:
    <android-sdk>/tools/android create uitest-project -n <name> -t 1 -p <path>
    The <name> is the name of the project that contains your uiautomator test source files, and the <path> is the path to the corresponding project directory.
  2. From the command line, set the ANDROID_HOME variable:
    • In Windows:
      set ANDROID_HOME=<path_to_your_sdk>
    • In UNIX:
      export ANDROID_HOME=<path_to_your_sdk>
  3. Go to the project directory where your build.xml file is located and build your test JAR.
    ant build
  4. Deploy your generated test JAR file to the test device by using the adb push command:
    adb push <path_to_output_jar> /data/local/tmp/
    Here’s an example:
    adb push ~/dev/workspace/LaunchSettings/bin/LaunchSettings.jar /data/local/tmp/

Running uiautomator Tests


Here’s an example of how to run a test that is implemented in the LaunchSettings.jar file. The tests are bundled in thecom.uia.example.my package:
adb shell uiautomator runtest LaunchSettings.jar -c com.uia.example.my.LaunchSettings
To learn more about the syntax, subcommands, and options for uiautomator, see the uiautomator reference.

Best Practices


Here are some best practices for functional UI testing with the uiautomator framework:
  • Ensure that you validate the same UI functions on your application across the various types of devices that your application might run on (for example, devices with different screen densities).
  • You should also test your UI against common scenarios such as in-coming phone calls, network interruptions, and user-initiated switching to other applications on the device.