Here is how I am registering a ContentObserver to listen to sent sms:
SendSmsObserver smsObeserver = (new SendSmsObserver(new Handler(), context));
ContentResolver contentResolver = context.getContentResolver();
contentResolver.registerContentObserver(Uri.parse("content://sms"), true, smsObeserver);
This is the SendSmsObserver class:
class SendSmsObserver extends ContentObserver {
private Context context;
SendSmsObserver(Handler handler, Context context) {
super(handler);
this.context = context;
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
queryLastSentSMS();
}
Now the question is that where should I put the top three lines of code? Currently I am writing it in the Activity's OnCreate method. But by doing this I am calling it every time the app is launched. I don't know if it is bad practice or not.
My requirement is that I should listen for sent sms outside my Activity lifecycle. This is working as expected, but should I always register it in the OnCreate method? Also I want to put the same lines in the onReceive() of a BroadcastReceiver to ensure that I am listening after rebooting the device.
UPDATE: BroadcastReceiver is somehow not registering the ContentObserver. I also tried to use getApplicationContext() as a context in BroadcastReceiver but to no avail.
JobScheduler
to monitor for content changes, akin to aContentObserver
. This is very useful, as what you want is not very practical on older devices.ContentObserver
. But since you cannot have a service running forever, there will be gaps in your coverage. And I am not certain if yourContentObserver
will be notified about SMS messages delivered while the device is in Doze mode or if your app is placed in app standby mode on Android 6.0+.