title: Android SMS inbox unread count issues
body: <p>I have created a little Android application that reacts to incoming SMS messages. The issue is that I cannot seem to be able to reliably get the number of unread messages in the inbox. </p>
  
  <p>Here's a bare minimum class to illustrate the issue. Sometimes it prints "Got SMS! Unread count: 0" and sometimes it prints "Got SMS! Unread count: 1". To me it would appear more logical if whenever the program flow entered that command the unread count would always be at least one. I have been testing this by sending SMS messages from one emulator to another (you can do that by sending the messages to the emulator number -- say, 5554).</p>
  
  <pre class="lang-java prettyprint-override"><code>import android.content.BroadcastReceiver;
  import android.content.Context;
  import android.content.Intent;
  import android.database.Cursor;
  import android.net.Uri;
  import android.util.Log;
  
  public class SmsReceiver extends BroadcastReceiver {
  private static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
  
  @Override
  public void onReceive(Context context, Intent intent) {
      Log.d("onReceive", "Got something: "+intent.getAction());
      if (!SMS_RECEIVED_ACTION.equals(intent.getAction())) {
          Log.d("onReceive", "Returning.");
          return;
      }
      Log.d("onReceive", "Got SMS! Unread count: " + getNumberOfUnreadMessages(context));
      // Do stuff
  }
  
  public int getNumberOfUnreadMessages(Context context) {
      final Uri SMS_INBOX_URI = Uri.parse("content://sms/inbox");
      Cursor inboxCursor = context.getContentResolver().query(SMS_INBOX_URI, null, "read = 0", null, null);
      int unreadMessagesCount = inboxCursor.getCount();
      inboxCursor.close();
      return unreadMessagesCount;
  }
  }
  </code></pre>
  
  <p>And finally, here's the relevant part from the AndroidManifest.xml file:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;receiver android:name=".SmsReceiver" &gt;
      &lt;intent-filter&gt;
          &lt;action android:name="android.provider.Telephony.SMS_RECEIVED" /&gt;
      &lt;/intent-filter&gt;
  &lt;/receiver&gt;
  </code></pre>
  
  <p>How do I get the correct number of unread messages? </p>
  
  <p><strong>Edit/Add:</strong> Alternatively, if it's a case of the broadcast being sent before the SMS is saved, is there a way to subscribe the app to listen for the event of a new SMS message being saved into the inbox?</p>