What's the deal with USB headphones?

Posted by

Why do these things exist? A while back, I bought a pair of Logitech H390 headphones. This is what they look like:

When I bought them, I didn't really spend a whole lot of time looking at the box, but the fact that the interface is USB is shown in that little info panel on the bottom-left. In retrospect, I probably should have spend more time reading that box because it turns out, USB is a horrible, weird interface for headphones and I can't for the life of me understand why they exist.

Cons of USB headphones

These are just the ones I ran into while using my headphones over the last year or so:

  • They only work in a couple of places. PC, sure. Maybe I could plug them into my Android phone with a USB-A to micro-USB adapter, but I never bothered to buy one in case it didn't work. A Ninentdo DS or practically anything else that's not a PC? Forget it!
  • Even when it works, because the headset shows up as a separate device, you can get yourself into weird situations where audio would continue routing to your main speakers and not the headphones. Both Windows (as of version 7, I haven't tried newer versions) and Linux have fairly clunky interfaces for choosing which output device to use. In most cases, with regular headphones, once you plug in all audio is automatically routed to the headphones.
  • Because the DAC happens inside the headphones, you can be pretty sure the quality of that hardward is nowhere near the quality of the hardware in your desktop computer.

Pros of USB headphones


Oh wait, I can think of one "pro". The Creative Tactic3D Rage headphones has illuminated ear cups. For some reason.

Connecting from your Android device to your host computer via adb

Posted by

Sometimes when I'm on the road, and using someone else's Wi-Fi (typically when I'm in a hotel), they will allow you to connect your phone and your laptop to the internet via their Wi-Fi. But, for security reasons, they typically won't allow your phone to connect to your computer over the Wi-Fi network. This make debugging certain applications quite difficult: I can't run a server on my laptop and have my phone connect to it.

But luckily, in recent versions of adb, a new command has been added: adb reverse. It's basically the opposite of adb forward, which lets you forward ports from the host to your device, adb reverse allows you to forward ports from your device to your host.

So let's say I have a server running on my host computer, listening on port 8080. I want my phone to connect to it, so I run:

$ adb reverse tcp:8080 tcp:8080

And then connect to on the phone and problem solved!

Like adb forward, the parameters correspond to server/destination ports. But in the case of adb reverse, the first parameter is the port on the device and the second is the port on the host you want to forward to.

A battery widget with support for monitoring your wearable battery level

Posted by

I released the first version of "Advanced Battery Monitor" towards the end of last year, to not much fanfare at all. I used it and a couple of my friends used it, and that's about it.

But since getting my hands on an Android Wear watch (Moto 360, to be precise), I added a new feature to my graph to also monitor the battery on the watch.

Here you can see my phone + watch battery level thoughout the day today:

The green line represents my phone's battery, the blue my watch's. I use both devices fairly heavily throughout the day, so I'll let you make of these graphs as you will.

The other feature I've added is the ability to export your battery data. The app only keeps battery data for up to a week, but you can export the whole data by tapping the widget to get into the "settings" and using the Export option.

The source code for the widget is available on github: https://github.com/codeka/advbatterygraph

And of course, the widget itself can be downloaded from the Play Store:


Playing around with a random level generator

Posted by

So, one of the things I've been toying with recently is the idea of a Diablo-style hack & slash. One of the most important aspects of the hack & slash is level generation. There's lots of ways you can generate levels and lots of different "looks" you can give your levels. I plan to explore a few different techniques over the next few weeks. My first attempt, which I've included below, gives a sort of cavernous look that I think would be good for boss levels:

The technique is quite simple, I "borrowed" the idea from this page. Basically, the algorithm runs as:

  1. Fill the board with random walls. Each square starts with a 45% chance of being filled.
  2. Each iteration, for each square, count the number of walls around that square. If there is more than 5, fill the wall in a new version of the map.
  3. Repeat step 2 until the map is "stable" (that is, until two iterations produce the same map).

In the example above, you just let it run normally, it'll do a few iterations, then complete the run in one go and pause for a few seconds so you can see the outcome. You can click "stop" then use the "reset" and "step" buttons to manually progress through the iterations.

There's a couple of problems with this, though. Firstly, it tends to make very open levels. I guess depending on the game, that may or may not be OK, but for our purposes, I think I'd like something a little more close-quarters. Another problem is that it produces overly "smooth" walls, that is, there are no sharp corners and no sharp points. Again, depending on your level design, that may or may not be OK, but I'd like to do something about it.

For the second problem, the solution is actually quite simple: just don't run the algorithm so many times. If we cap the number of iterations to, say, 10, then we end up with more jagged walls. But that introduces an extra problem: sometimes it will leave behind very tiny "islands" of walls, which the old alorithm would have smoothed away. That can be fixed by a "manual" cleanup afterward where we simply remove the small islands.

For the first problem, we modify the algorithm slightly:

   Map.prototype.iterate = function() {
      var newMap = new Map(this.width, this.height);
      for (var x = 0; x < this.width; x++) {
        for (var y = 0; y < this.height; y++) {
          if (this.numWallsWithinSteps(x, y, 1) >= 5) {
            newMap.setCell(x, y, 1);
          } else if (this.stepNo < 6 && this.numWallsWithinSteps(x, y, 2) < 2) {
            newMap.setCell(x, y, 1);
      newMap.stepNo = this.stepNo + 1;
      return newMap;

The above algorithm can be seen in the map below:

As you can see, this version results in much more "cramped" level than the first version. You can download the full code for the final version here.

This is a pretty simple algorithm and produces nice levels for boss fights, but next time, we'll want to try a slightly more complicated algorithm for generating the room/corridor style levels that you come to expect.

Detecting leaked Activities in Android

Posted by

So War Worlds has, for quite some time, been plagued with various memory issues. One of the problems is that Android in general is pretty stingy with the heap memory it gives to programs, but the other is that it's actually very easy to "leak" large chunks of memory by accidentally leaving references to Activity objects in static variables.

There's not much that can be done about the former, but the latter can be fairly easily debugged using a couple of tools provided by Android and Java.

Detecting leaked Activties

The first step is figuring out when Activties are actually leaked. In API Level 11 (Honeycomb), Android added the detectActivityLeaks() method to StrictMode.VmPolicy.Builder class. All this method does is cause Android to keep an internal count of the number of instances of each Activity class that exist on the heap, and let you know whenever it hits 2.

When you get a StrictMode violation, there's a few things you can do, you can have Android kill your process, you can log a message, or you can do both. To be honest, neither of those things is particularly helpful because when you've got a leak what you really want is a dump of the heap so that you can analyse it later.

Luckily for us, the StrictMode class writes a message to System.err just before it kills the process, so we can do this little hack to hook in just before that happens and get a HPROF dump just in time:

private static void enableStrictMode() {
  try {
    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()

    // Replace System.err with one that'll monitor for StrictMode
    // killing us and perform a hprof heap dump just before it does.
    System.setErr (new PrintStreamThatDumpsHprofWhenStrictModeKillsUs(
  } catch(Exception e) {
    // ignore errors

private static class PrintStreamThatDumpsHprofWhenStrictModeKillsUs
    extends PrintStream {
  public PrintStreamThatDumpsHprofWhenStrictModeKillsUs(OutputStream outs) {
    super (outs);

  public synchronized void println(String str) {
    if (str.startsWith("StrictMode VmPolicy violation with POLICY_DEATH;")) {
      // StrictMode is about to terminate us... do a heap dump!
      try {
        File dir = Environment.getExternalStorageDirectory();
        File file = new File(dir, "strictmode-violation.hprof");
        super.println("Dumping HPROF to: " + file);
      } catch (Exception e) {

Essentially, what we do is, we set up StrictMode to kill us, the replace System.err with a hack subclass of PrintSteam that checks for the message StrictMode prints and generates a heap dump right then and there.

It's ugly, but we only have to do it in debug mode anyway, so I think it's OK.

Analysing the dump

Next, we have to copy the .hprof file off the device (you could use adb pull for that, but I like ES File Explorer). One important step is converting the .hprof file from Dalvik format to normal Java format. There's a handy-dandy tool called hprof-conv in the Android SDK which does the conversion for you.

Once you've got a HPROF file a format that can be read by the standard Java tools, the next step is actually analysing it. I was using the Eclipse Memory Analyzer tool, but anything will do, really. The first thing we need to do is find out which objects are leaking. Luckily for us, StrictMode prints out which activity is leaking, so we can start there:

01-15 17:24:23.248: E/StrictMode(13867): class au.com.codeka.warworlds.game.EmpireActivity; instances=2; limit=1
01-15 17:24:23.248: E/StrictMode(13867): android.os.StrictMode$InstanceCountViolation: class au.com.codeka.warworlds.game.EmpireActivity; instances=2; limit=1

So it's detected two copies of the EmpireActivity class. We fire up the Memory Analysis tool in Eclipse, and go to "List objects ... with incoming references" and enter our offending class, "au.com.codeka.warworlds.game.EmpireActivity". And just as StrictMode said, there's our two instances:

Now, how do we determine where they're being held? Right-click one of them and select "Path to GC Roots ... with all references", which will bring up something like this:

If we go with the assumption that the leak happens in our code and not in the framework (usually a pretty good assumption) the only object holding a reference to this activity is our FleetList class. If we expand that out a few times, we can follow the references all the way back to the mSpriteGeneratedListeners member of StarImageManager.

What the StarImageManager class does is it generates (or loads from disk) the bitmaps used to display stars. It has a list of objects that are interested in knowing when the star images are updated (generating them can take a while). What was happening here is that the FleetListAdapter class was adding itself to the list of classes interested in receiving updates from StarImageManager, but never removing itself from that list.

By fixing that bug, I managed to squash one the biggest memory leaks in the game.

Further work

One thing this has highlighted to me is that my system of highly manual event pub/sub is probably not a great idea. Scattered all throughout the code are lots of these "lists of classes who want to subscribe to my event". Management of those lists is all manual, firing the events is manual, and it's actually been a bit of a source of problems in the past (e.g. with events firing on random threads and whatnot).

So the next big chunk of work will be replacing all of these with some kind of unified EventBus pattern. I quite like the implimentation of code.google.com/p/simpleeventbus, in particular I like how it uses WeakReferences to hold the event subscribers (which would make the above memory leak non-existent).