I'm playing around with a small notification app. My basic requirements are: when an SMS comes in, turn on the LED. When it gets read, turn it off. The first part seems easy enough: I have a BroadcastReceiver
with the following in my manifest:
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
However, the second part has proven more tricky. Currently, I have a service which starts up whenever a message comes in. It runs a TimerTask
every 15 seconds which runs this code:
int count = 0;
Uri providerURI = Uri.parse( "content://sms" );
Cursor cursor = this.getContentResolver().query( providerURI, null, "read=0", null, null );
if( cursor != null ) {
try {
count = cursor.getCount();
}
finally {
cursor.close();
}
}
return count;
It seems to work well enough. When the count is 0, I cancel the TimerTask
and stop the service. However, I'm concerned about battery life. Is there any sort of general notification for when the number of unread messages changes? Or any better way of doing this?
You can use ContentObserver. I suppose when a new message comes into sms inbox, you will get a notification (by content observer), on the other hand, when a sms has been read, it will be removed from inbox, and also you will get another notification.
ps, Use ContentObserver observing on content://sms/inbox