I have a Service that constantly works in the background and never dies. One of his appointments is to check the status of the phonebook of contacts, i.e. its database: if the contact has been deleted from it, changed or added a new one, then the service should respond to it. The question is how the service will find out about it. The most "stupid" solution is to make a periodic check of the database of contacts, but this option is poor ... One person told me that you can use ContentObserver, but you need to kill it with the death of the application. If anyone knows, please suggest whether it is possible to register ContentObserver in the Service and not kill it so that it reacts to changes in the database of contacts. If it is possible, will it react even when the phone is locked (CPU in sleep mode), or will it be necessary to use PowerManager to wake up the processor?
1 answer
- It will react if you make the right bind of the service and application (bind is the process of getting the application pointer to the
Service). After bind, you will need to drop a pointer to the ContentObserver in the contacts database, which will be created inside the service.
Clients can also use Context.bindService () to obtain a persistent connection to a service.
- But unfortunately the service will not live forever either, the time will come and its axis will beat itself. Read about the lifecycle service.
It can be a problem. If this happens, the system will try to restart the service later.
- The fact is that it will not stop, if you make it foregraund, it allows the service to live always without exception, that the system will not crash it, even if there is not enough memory. Checked - BORSHEVIK
- Question. Why should the application get a pointer to the service? Is it possible to confine myself to the service itself, or did I misunderstand something? - BORSHEVIK
- Do not confuse the Service class with its instance. You can, of course, make a static link to the
Service/ContentObserver(the Singleton pattern), but this is not exactly ice. It may happen that theServicehas not yet started, and there is already a link to it. - Barmaley
|