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 127.0.0.1:8080 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);
      newMap.clearMap();
      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()
        .detectActivityLeaks().detectLeakedClosableObjects()
        .detectLeakedRegistrationObjects().detectLeakedSqlLiteObjects()
        .penaltyLog().penaltyDeath().build());

    // 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(
        System.err));
  } catch(Exception e) {
    // ignore errors
  }
}

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

  @Override
  public synchronized void println(String str) {
    super.println(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);
        Debug.dumpHprofData(file.getAbsolutePath());
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
}

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

Unicode support in MySQL is ... 👎

Posted by

For the last few days, I've been getting some strange error reports from the War Worlds server. Messages like this:

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98\xB8. ...' for column 'message' at row 1
   at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
   at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
   at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
   at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815)
   at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
   at com.jolbox.bonecp.PreparedStatementHandle.executeUpdate(PreparedStatementHandle.java:203)
   at au.com.codeka.warworlds.server.data.SqlStmt.update(SqlStmt.java:117)
   at au.com.codeka.warworlds.server.ctrl.ChatController.postMessage(ChatController.java:120)
   . . .

Now, that string which MySQL complains is "incorrect" is actually the Unicode codepoint U+1F638 GRINNING CAT FACE WITH SMILING EYES, aka 😸 -- a perfectly valid Emoji character. Why was MySQL rejecting it? All my columns are defined to accept UTF-8, so there should not be a problem, right?

When is UTF-8 not UTF-8?

When it's used in MySQL, apparently.

For reasons that completely escape me, MySQL 5.x limits UTF-8 strings to U+FFFF and smaller. That is, the "BMP". Why they call this encoding "UTF-8" is beyond me, it most definitely is not UTF-8.

The trick, apparently, is to use a slightly different encoding which MySQL calls "utf8mb4" which supports up to 4-byte UTF-8 characters.

So the "fix" was simple, just run:

ALTER TABLE chat_messages
   MODIFY message TEXT CHARACTER SET utf8mb4
                       COLLATE utf8mb4_unicode_ci NOT NULL;

And so on, on basically every column in the database which could possibly include characters outside the BMP. But that's not enough! You also need to tell the server to use "utf8mb4" internally as well, by including the following line in your my.cnf:

[mysqld] ​character-set-server = utf8mb4

Now presumably there is some drawback from doing this, otherwise "utf8mb4" would be the default (right?) but I'll be damned if I can figure out what the drawback is. I guess will just moniter things and see where it takes us. But as of now, War Worlds support Emoji emoticons in chat messages, yay!

Addendum

If you're just seeing squares for the emoji characters in this post, you'll need a font that supports the various unicode emoji blocks. I've used the Symbola font (which you can get here) with good results.