Android and Gradle : migrating to the new project structure

Recently, I decided to sit down and restructure an app the Gradle way. I had previously migrated the project to Gradle, and made the switch to Android Studio, but I had kept the legacy project structure:

project/
   AndroidManifest.xml
   src/
   res/
   assets/

This app has 2 flavors: free and paid. To support them, all of the common code was in a library project, which was used by free and paid projects, for a total of 3 projects. There was a lot of duplicated code with the multiple manifests, and wrapper classes, as well as code interrogating the package name to determine which features should be enabled. Gradle solves all of that mess quite nicely.

To start, I moved all of the library project code into the default Gradle structure, which looked something like this:

mv src/com/myapp/*.aidl src/main/aidl/com/myapp/
mv src/* src/main/java/
mv AndroidManifest.xml src/main/
mv res src/main/
mv assets src/main/

This puts everything under the src directory, where Gradle expects to find its source sets. Since this code was common to both the free and paid flavors of the app, everything went into the main source set.

As those files were now in the default locations, I removed all of these custom locations from build.gradle.

# don't need these anymore :)
java.srcDirs = ['src']
aidl.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']

I also switched the plugin in build.gradle from android-library to com.android.application, since this would become my single project for building both flavors of the app.

At this point, based on the buildTypes in build.gradle, I could assemble debug and release apps. Since I have 2 flavors, I defined them alongside the buildTypes in build.gradle as productFlavors.

buildTypes {
    ...
}
productFlavors {
    free {
        applicationId = "com.myapp"
    }
    paid {
        applicationId = "com.myapppro"
    }
}

With Ant, I had multiple AndroidManifest.xml files which had unique package names, but with Gradle a single file can be used with the package name injected while building. This is done using applicationId, which is built into the com.android.application plugin. Custom variables are also supported. For example, this app uses the Backup API, which requires a key unique to the app. For each productFlavor, I added a variable in the custom set manifestPlaceholders.

free {
    applicationId = "com.myapp"
    manifestPlaceholders = [
        backupApiKey: "myFreeBackupApiKeyValue"
    ]
}
paid {
    applicationId = "com.myapppro"
    manifestPlaceholders = [
        backupApiKey: "myPaidBackupApiKeyValue"
    ]
}

Custom variables can then be referenced in the AndroidManifest.xml like this:

<meta-data
    android:name="com.google.android.backup.api_key"
    android:value="${backupApiKey}" />

If  you’re running into build errors when injecting values, you may need to specify the new manifest merger in build.gradle:

android {
...
    useOldManifestMerger false
...
}

The new manifest merger has been the default since version 11 of the gradle plugin.

The free flavor of the app has Ads in it, which requires defining an activity in the manifest. That definition isn’t need in the paid flavor. This is where the source sets come in. I have an AndroidManifest.xml in the main source set. Alongside the main directory, I added directories for free and paid.

src/
    free/
    main/
    paid/

In the free directory, I only need a slimmed down manifest with the differences:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application>
        <activity
    android:name="com.google.android.gms.ads.AdActivity"
    android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
    </application>
</manifest>

Gradle, through the com.android.application plugin, merges the manifests together, so that the free flavor has everything it needs, without effecting the paid flavor.

The last difference between flavors was the app name. As with the manifest for the free flavor, I created a strings.xml in the paid source set with only the changed strings, as they will be merged with all of the common strings in the main source set.

The result was the only differences to maintain between the two flavors are the manifest and strings files, rather than two entire projects.

Bonus:

Those Backup API keys can be loaded from an external file, so that they’re not necessary shared along with the build.gradle file. For example, a gradle.properties file in the root of the project might contain:

free.backup.api.key=MyFreeBackupApiKey
paid.backup.api.key=MyPaidBackupApiKey

Those variables would then be accessed in the build.gradle file like this:

manifestPlaceholders = [
    backupApiKey:
        project.property("free.backup.api.key")
    ]

Quick Tip: How to install or uninstall APKs on multiple Android devices with just one command

Recently, while working on a mobile project, I found myself spending a lot of time connecting a device, uninstalling the previous version of the Application Under Test (AUT), installing the new one, and then disconnecting the device, just to do it again on another 6 or 7 devices (I would like to talk about why it is better to test on actual devices than in a simulator, but that topic deserves its own blog post).

For this post, I want to describe a solution I found to manage all of the attached devices with a single command. First I obtained this device, (you can get it thru Amazon here)which is just one of many different options available, depending on the arrangement, number of ports, shape, etc. I picked this one because it was cheap and the switches come in handy because we can exclude devices just by switching OFF that specific device and there’s no need to connect/disconnect any device.

usb hub

Just adding ports to your computer helps, but we need to get the most of them. When working with Android devices and we want, for example, to install an app, we have to type the following command in the terminal:

adb install -r path/to/the/app/to/install.apk

 This works fine when you have a single device attached because adb is designed for a single device, but when you have multiple devices attached, you get an error,  like so:

- waiting for device -

error: more than one device and emulator

- waiting for device -

error: more than one device and emulator

- waiting for device -

Failure

 We need to specify to adb the device we want to send the command to. To do so, we need to first get the device ID of every device connected by typing:

adb devices

This command will return something like:

List of devices attached

04544fawebf0b595dc device

13928weff7c device

 Then to install on each device, we would need to copy each of these ids, and include them in the following command.

adb -s (deviceID) install -r path/to/the/app/to/install.apk

If I were to do this, I would need to copy each deviceID, type the above command seven times, pasting a different deviceID each time. Although this is better than connecting and disconnecting each device, this is still not the most productive way.

Searching the web for a solution, I found on Stackoverflow a script that solves this problem nicely.

Installation

First, copy and paste the following code in a new file called adb+

#!/bin/bash
# Script adb+
# Usage
# You can run any command adb provides on all your currently connected devices
# ./adb+ <command> is the equivalent of ./adb -s <serial number> <command>
#
# Examples
# ./adb+ version
# ./adb+ install apidemo.apk
# ./adb+ uninstall com.example.android.apis
adb devices | while read line
do
  if [ ! "$line" = "" ] && [ `echo $line | awk '{print $2}'` = "device" ]
  then
      device=`echo $line | awk '{print $1}'`
      echo "adb -s $device $@ ..."
      adb -s $device $@
  fi
done

Then store this new file in the folder containing adb within your Android SDK installation folder. This should most likely be the  platform-tools folder.

Usage

Using the script is very simple. When we have more than one device connected (always use adb devices first, just to make sure all your devices are connected) we just need to work as if we were using adb, with any “adb” command replaced with “adb+”. For example, if we want to install an app:

adb+ install -r path/to/the/app/to/install.apk

This gives us something like:

04544fabs23f0b595dc install -r /path/to/your/app/name_of_the_app.apk ...

4619 KB/s (13249277 bytes in 2.800s)

    pkg: /data/local/tmp/name_of_the_app.apk

Success

1399834vskj28f7c install -r/path/to/your/app/name_of_the_app.apk ...

3608 KB/s (13249277 bytes in 3.585s)

    pkg: /data/local/tmp/name_of_the_app.apk

Success

Troubleshooting

If you find that you get the following when you attempt to run adb+

-bash: adb+: Permission denied

Your bash script simply isn’t executable. This is very easy to fix, run this command from the directory containing the script:

chmod 755 ./adb+

Now try it, you should see what you were expecting.

That’s it. The new script will go thru each device, performing the same command.  The app will install on all devices connected, and you will save a few minutes. What do you think? Is this going to help you with your mobile testing? Let us know!

The Idea Factory: Bell Labs and the Great Age of American Innovation, Book Cover

What MeetMe is reading this month…

 We bring you another installment of What MeetMe is reading this month…  Yet again, an eclectic mix. You’ll find writing that will inspire you to exercise your imagination and create, communicate more effectively, consider the pursuit of  happiness and simplicity, and of course, a little something to make you go WAH?!?!?

featured:

 

ideafactory

“An incomplete list of things invented at Bell Labs during its heyday: lasers, fiberoptic cables, satellite communications, cell phones, the C programming language, solar panels.

My favorite story in here: John Bardeen and Walter Brattain plug away for years to find the right materials to create the first functioning transistor.  Their boss William Shockley, who had laid some of the theoretical framework for their achievement, gets angry about not receiving enough credit.  So he stays up all night in a hotel room on New Year’s Eve writing out 30 pages of notes describing a better approach, and is able to prove out the concept in a few months.  His version becomes the standard.

The book will get you thinking about innovation and the circumstances that lead to it.  Much is a reinforcement of the now-fashionable idea that all invention is iteration, not the solitary genius model you might have learned in school.  But that new dogma is also challenged, or at least tempered.  Consider Claude Shannon, who showed up for work whenever, spent much of his time creating electromechanical mice and riding around the office on a unicycle, and knocked out the whole foundation of Information Theory in between games of chess.”

Roger Taylor

 


 

 “There’s one main theme to Essentialism: prioritizing the important things and throwing away the rest.  While this sounds simple in concept, whether in a professional or personal context, we tend to often prioritize incorrectly or choose to include non-important tasks due to outside pressures.  The audiobook weighs in at over 6 hours for this central topic, so it definitely gets repetitive, but the overall message is a good one.”

logic_and_design

Logic and Design, Revised: In Art, Science, and Mathematics

by Krome Barratt

Joe Szymanski

Rich Friedman

Web Developer Screenshot

The Best Browser Add-Ons for Quality Assurance

Recently, Firefox 29 was rolled out with a new redesign and, while downloading and installing it, I realized all the history Firefox and I have together. I believe the first version I installed was 2.7; since then we’ve been BFFs.

I’ve seen some browsers rise, grow, and die, like Flock (based on Firefox) and Rockmelt (based on Chrome). I have also seen others that always have been there, like Opera and Internet Explorer, but they have never been good enough.

As a Quality Assurance Tester, Chrome became a necessity to test because of its dominance in the market and, while I have grown accustomed to it, I still prefer Firefox.We testers need tools to help replicate user errors on the websites we’re testing, but the browsers alone are not enough for in-depth needs. This is when we can get help from some add-ons that can extend our browsers’ capabilities.

Below are some of the add-ons I use frequently and that all testers should utilize. This list is mostly focused on Firefox, but most of these add-ons (or similar ones) are also available for Chrome.

Fireshot

One of the most common tasks of a tester is taking screenshots. We need to take screenshots to back up our findings and sometimes we need to show the error to the developer. There are many of apps for this task, but my favorite is Fireshot. It has two killer features.

First, it is capable of taking screenshots of a complete page, even when the page is not showing completely in the browser. The second is the ability to add annotations within the app with some other great tools in it. These are important to us as testers because we can point out to our dev/design teams, stuff that is out of place, or bigger/smaller that it should, we can annotate steps to follow in the current page, to replicate some issue, etc. That helps or dev team to visualize what we are reporting and helps them realize faster where in the code that could be fixed.

fireshot screenshot

Another interesting feature is that once we install it in Firefox, it will prompt for installing it on Chrome and Internet Explorer. Unfortunately, this add-on is not available on Mac for any browser, but there are some other pretty good options for this OS. I’ve been using uploadscreenshot.com for my Firefox on Mac, and although is not as complete as Fireshot, it has been working pretty well for me. It can also take screenshots of a complete page, even when the page is not displaying completely on the browser. Fireshot is available for Free and there’s a PRO (paid) version for about $40  for a Lifetime License.

Firebug

This is an add-on that has been around for a while with Firefox. Although now all browsers have their own debugger tools, I still consider this one a must-have. I keep liking it because I’m used to it, and its interface, in my opinion, is more friendly. If we compare it to Chrome’s native tool for example, Firebug is easier to use because everything is one or maybe two clicks away, in Chrome’s native tool there’s some cases we have to navigate through some three-like menus to get some kind of info., like cookies.

Firebug Screenshot

By using it we can edit the cookies, delete any specific cookie to replicate certain behavior, we can navigate through the HTML code of the current website and its CSS, we can even modify it and see the changes on the fly, for example, to fix some little CSS issue, we can give a suggestion on how to fix it, or actually find the part of the code that is causing the problem and that will save some time to our dev to fix the problem. We can also see errors from the console, copy and paste the response of a call and report back to our dev with that information, that would help them debug the issue and a lot of more stuff. This is, if not the most, one of the most important tools for a Tester. It is also expandable, we can install addons on it like Yslow or Firepath (more on this one later).

Every web tester should know how to use Firebug or any of the native alternatives for all the browsers. Firebug is available for Firefox in Mac and Windows and it is also available in a pretty light version for Safari in Mac.

Measure It

Lets say that we want to make sure that the measures of that textbox or that other button meet the requirements described in the specs. We could use Firebug to search through the CSS of the application. However, sometimes the code is not that clean or we can have problems finding an specific item. Measure It is a pretty good tool for this situation. This add-on adds a button into our browser that when clicked will let us draw an area and tell us the measurements on pixels of it. Easy and quick.

MeasureIt Screenshot

It is currently available for free in Firefox and Chrome, in both Mac and Windows.

ABP

AdBlock Plus is a tool that can be very useful if we are not currently working with ads testing or our app doesn’t need them to work. This add-on blocks all the ads from a website based on specific filters we choose. With this add-on, our app can work faster because it doesn’t load them, bringing better performance to our app and less distraction to us.

ABP Screenshot

However, we have to be careful with this add-on as it can hide some bugs that our users are experiencing. For example, when an ad is broken, it can cause a bug in our app and we won’t be aware of it if we have this add-on active. Or, worse, it can cause us a momentary panic if it inadvertently shows us a bug that is not happening when the ads are present in our app. When the layout of an app depends on the ads, if the ads are not present, the layout might break. I’ve always find it useful to get my Application Under Test (AUT) better performance for my tests. This add-on is available for free in Firefox and Chrome for both Mac and Windows.

Link Evaluator

As its name implies, this add-on evaluates all the links in a given page and it colors them green, yellow, or red depending on their response. It colors them green when it receives a 200 or 400 response, and red if it gets a 404, 500, or some other error response. It is very useful to check all the links in a page quickly and to avoid missing any of them. In this way, the tester doesn’t need to click on each one to see if there are any dead ends or some other bad user experience.

Link Evaluator Meetme

It is available for free in Firefox on Mac or Windows, and, although it is not available for Chrome, there are other options for this one. The most similar is Link Checker that is available for free on Mac and Windows.

Dummy Lipsum

This add-on helps us by generating dummy text. Suppose we want to fill a form or see how some text looks in a page. After installing this add-on, we would have a button on our browser’s toolbar that, on click, will bring us a dialog where we can pick between some options, like how much paragraphs or words, if we want to include punctuation or html tags, etc.

Dummy Lipsum Screenshot

After selecting all our options, we just need to click Generate button, then Copy to Clipboard button and then we can paste it anywhere.

This add-on is available for free only for Firefox on Mac and Windows. There are similar tools available there for Chrome or any other browser, like YALIG (Yet Another Lorem Ipsum Generator) that is available for free in Chrome in both Mac and Windows. There are other fun Lorem Ipsum Generators that are not add-ons, but are useful and will add a touch of creativity to our tests. We can add them to our bookmarks for easy access.

  • Fillerama generates dialogs from shows like Futurama, Dexter, Arrested Development and more.
  • Pirate Ipsum  generates random pirate like sentences.
  • Obama Ipsum generates random President Obama quotes.
  • Trollen Ipsum generates trolling phrases between, for example,  Apple Fans to Android Fans and viceversa.
  • Quote Ipsum generates random famous quotes.
  • Picksum Ipsum generates phrases from movie dialogs from characters of Michael Caine, Jim Carrey, Clint Eastwood and Morgan Freeman.

Web Developer

This tool adds a menu to our browser with a whole world of options that can help us to make our day-to-day work a little bit easier. What I’ve used it for is the cookies menu, which lets us clear cookies completely. Sounds like nothing special, right?. Where this is useful and different is that it lets us clear just the cookies from our current session or just current domain cookies. This is a major help for when we have login credentials for various sites and we want to clear cookies for just one of them. With this tool we can also play with the CSS, disabling it, changing it, adding stylesheets to the current page.

Web Developer Screenshot

We can also disable the cache, disable cookies, disable javascript. All that can help us to test certain conditions in an application. It can help us to work with Forms, clearing all fields, with just one click, auto-filling forms, etc. It can also work with images, for example it can display image sizes, disable all images, display alt texts and tons of other features. This one is a must have!

This add-on is available for free in Firefox, Internet Explorer, Chrome, and Opera for Windows and Firefox and Chrome in  Mac OSX.

URL to QR code

Not talking about a specific add-on here, there’s a bunch of them out there for all browsers and OS combinations. What does they do? Very simple, they generate a QR Code using the URL for the current viewing web page. Something like:

When we use a mobile device like a phone or a tablet and we scan this QR Code, it will open the browser in the device and navigate to that URL. In that way, we can easily type our URL in our desktop browser, then take a picture with the device with a QR Code reader. In this way, we would not need to type in those tricky small touchscreen keyboards. This saves some time and hassle from typing if we are working on a browser-based mobile app or website.

URLToQRCode Screenshot

I have tried URLtoQRcode on my Firefox + Mac environment. On my Chrome in both, Mac and Windows I have QR Image from URL. But in my Firefox + Windows I use Etao QR Code, all them are practically the same thing and all they are free.

iMacros

The first automation tool in this post, iMacros allows us to record steps that we are doing manually and while recording it saves those steps as code. Once recorded, we can edit, add, or remove steps on it’s own IDE. And finally we can play them over and over again. While not the most popular app available for this, I find it as good or better than Selenium, the most popular tool out there.

iMacros Screenshot

iMacros has its own versions free for Firefox, Chrome, and Internet Explorer in both Mac and Windows. In that way, we can create our script in Chrome and play it there, but also in Firefox and Internet Explorer.

There are a few caveats preventing it from being perfect. This free add-on has some command restrictions on its Chrome and IE versions, compared with its Firefox free version. And the Firefox free version has some other restrictions that the PRO version doesn’t have. The PRO version is more complete, allowing us to use their own browser, and code scripts in almost all well-known programming languages. However, it is very expensive. For the frugal-minded, the Firefox version is pretty capable–we can build pretty complex scripts there.

Selenium IDE

Who hasn’t used or heard about this tool? It’s free, compatible with all major browsers and OS (including Linux), and programming languages. What else we can ask for, right?

Selenium IDE Screenshot

This IDE is pretty much the same thing as iMacros, letting us record steps made manually and play them back later. All steps are recorded in Selenesse, the Selenium language. This tool has other add-ons that let us export our scripts to other languages as python, ruby, php, java, etc. It also has its own add-ons created by the community that further expand the capabilities of this IDE.

Firepath

Last but not least, now that we are talking about automation, I would like to talk about Firepath. Who hasn’t had problems with the way Selenium’s playback functions from time to time? Firepath is an add-on for Firebug. It lets us select an element from the web page we are on and it will tell us its Xpath or CSS selector. It also works backwards–we can specify an Xpath or CSS selector in the box and it will mark for us the element that meets that selector. We can then use that information in our scripts.

FirePath Screenshot

So, what do you think about these tools? Do you like them? Are you already using any of them? Which ones have I missed? Give us a shout and let us know!

Open Talk: A Whirlwind Tour of Gradle for Android with Mark Murphy, June 17

A Whirlwind Tour of Gradle for Android

The Android tools team has been hard at work developing an Android plugin for the Gradle build system, with an eye towards Gradle for Android replacing the venerable Ant for automated builds. Gradle for Android is also used by Android Studio, the new Android IDE, for its builds. In this presentation, we will explore what Gradle for Android is, what problems it solves, how to get started playing with Gradle for Android, and how to take advantage of some of its basic features. Attendees will leave with a better understanding of why Gradle for Android is important for all Android developers in 2014 and beyond.

About the presenters

Mark Murphy is the founder of CommonsWare and the author of The Busy Coder’s Guide to Android Development. He is active in supporting the Android developer community, from answering questions on StackOverflow to publishing sample code and reusable components as open source.

A three-time entrepreneur, his experience ranges from consulting on open source and collaborative development for the Fortune 500 to application development on just about anything smaller than a mainframe. He has been a software developer for nearly three decades, from the TRS-80 to the latest crop of mobile devices. A polished speaker, Mr. Murphy has delivered conference presentations and training sessions on a wide array of topics internationally.

RSVP Here.