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.
A
Handleris used in conjunction with aLooperto execute a queue of tasks one by one. In the case of a ContentObserver, itsonChange()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 aLooperfor that thread usingLooper.prepare();The reason you don’t need to create a
Looperfor the main thread is that it is automatically created for you.For a nice explanation of how Handler & Looper work, check this article.