Handler to sms ContentObserver
-
24-05-2021 - |
Question
I have found this code in two posts here:
String url = "content://sms/";
Uri uri = Uri.parse(url);
getContentResolver().registerContentObserver(uri, true, new MyContentObserver(handler));
But I don't know what this handler passed in the constructor of MyContentObserver is.
I want to register a ContentObserver in "content://sms//sent" to be notified when Android sends a sms, and in the documentation of ContentObserver says that the method OnChange will be called from the handled passed in the constructor.
Solution
A Handler
is used in conjunction with a Looper
to execute a queue of tasks one by one. In the case of a ContentObserver, its onChange()
method might be called multiple times. To queue these calls and execute them sequentially, you need to supply a handler.
If you want onChange()
to be executed in the main thread, simply create a new Handler like: Handler handler = new Handler();
and pass it.
But if you want onChange()
to be executed in another thread, you first need to create a Looper
for that thread using Looper.prepare();
The reason you don't need to create a Looper
for the main thread is that it is automatically created for you.
For a nice explanation of how Handler & Looper work, check this article.