After the pending intent has started your AppWidgetProvider, you need to perform some logic on behalf of the calling application (in this case, the Home screen application). In the following sections, I show you how to perform time-sensitive work on behalf of the caller.
Before I hop into the code, it's best to understand how the work will be done in the AppWidgetProvider. Due to the nature of remote processes and how resource-intensive they can be, it's best to do all work inside a background service. I will be performing the changing of the brightness mode via a background service.
Why should you use a background service for such a trivial task as changing the device brightness mode? Well, it has to do with avoiding Application Not Responding (ANR) errors.
Any code that executes for too long without responding to the Android system is subject to the ANR error. App widgets are especially vulnerable to ANR errors because they are executing code in a remote process — they execute across process boundaries that can take time to set up, execute, and tear down — the entire process is very CPU-, memory-, and battery-intensive. The Android system watches app widgets to ensure that they do not take too long to execute. If they do take an extended period of time to execute, the calling application (the Home screen) locks up and the device is unusable. Therefore, the Android platform wants to make sure ...