J2ME has a nice feature: PushRegistry. You can “register” an event which then starts up automatically your application.
This of course also works for receiving SMS on specific ports. (SMSes sent to a non-standard port will not show up in the inbox).
If such an SMS comes in on – lets say port 4321 – your application starts up, you can then easily find out that your app was woken up by such an event and read the SMS via the java messaging API. (Create the MessageConnection using a Connector, then call the method receive to get it).
But there is an interesting issue:
if during your tests once your application crashes between starting up and the call to receive, the message will remain in the SMS queue. Now if a new message comes in, your application is triggered, but if you now call the receive method, you will get the first message in the queue and not the actual one.
Now this gets a little bit tricky, as you can not enumerate the message queue and the call to receive is blocking – so you can not just “read until the last message is read”, because you don’t know when the end of the queue is reached and if you call receive once more, your application is stuck until the next message arrives.
Gladly, there also exists the method to setup a messagelistener, which is called once for every message in that queue. But now you have the problem, that this is done asynchronously, so you can not wait until the last message is received by this listener and then continue with it.
The solution is: if your application is triggered, read the message, then install the listener to purge the rest of the queue. If there already was a message in the queue, you have read the wrong one, but at least all following calls will work.