30 January 2011

Android SMS XML Parsing

Using XML with SMS sounds kinda dumb.  After all an SMS text is only 140 characters (or less ...) and XML is horribly bloated.  But if the originating application is using XML and SMS is the convenient transport, then nothing's too stupid.

There's plenty of articles that describe the various Android options for parsing XML.  SAX, DOM, and XML Pull.  Actually, I'd prefer to use XStream for quick XML read/writing but with the XStream jar around 500k, it's not a good droid choice.

I'm going to quickly show you how I intercept incoming SMS messages and route them to an XML parser if the message starts with a tag (in my case <evt>).  After parsing, I then look at fields in the message and then start other processing that I won't go into here.

I'll show you some quick screen shots of the code and attempt to explain.  At the end of the article, you'll find a link to the entire Eclipse project.  This has been tailored down quite a bit from how I'm using it.  It simply sniffs incoming messages and then displays XML fields.

An example incoming XML SMS message looks like this.  I'm receiving XML SMS messages from several sources such as email (like below) and from Twitter (like I blogged about here and here).


Even though my sample SMS XML message shows line breaks so the XML is nicely formated, you don't want to do this.  Don't waste a precious character on a break.  Run all the XML tags together.  My XML Pull Parser class is expecting no line breaks.

In AndroidManifest.xml, add a receiver for the SMS_RECEIVED action to your application and add RECEIVE_SMS to your permissions:


...

In your receiver class (the one that you named in your manifest file), extend BroadcastReceiver and implement onReceive.  After jumping thru a few hoops to get the message content, determine if this is a message you care about.  My "special" messages all have the XML tag "" after a few header characters depending on the source (such as email or Twitter).  If I find this tag, I display a quick toast and then send the message for XML parsing.

 
Here's an example Eclipse app that parses incoming SMS message and checks if they have the tage.  If so, a toast message is displayed and the sent of for XML parsing.  After parsing, the app simply display the contents of a few of the XML tag contents.

My deployed app is actually an Android service, not a simple app like this example.

Download the example.

What do you think? Leave a comment.

1 comment:

  1. xml is a very interesting language to be used and contain the data object model or abbreviated DOM.tutorial very good and hopefully can help me in building a web application thanks

    ReplyDelete