Search code examples
androidandroid-sqliteandroid-contentproviderandroid-lifecycle

Update Activity data from service when its paused


Lets say I have an activity that has a data object. It updates its gui component based on that object. Now lets say that it is paused ( OnPause is called) but not stopped or destoryed

Meanwhile , a push notification is received ( intentservice is started) and I need to update that object with the push notification object so I gui is updated when the app is resumed.

I thought about sending a broadcast to the activity so it can update its dataobject But I read somewhere that when activity is paused then broadcasts are not received.

What should I do in this case?


Solution

  • The hard but correct way to do this is to build your own custom ContentProvider for your app and update all data received from web services and push notifications to this ContentProvider. When the Activity comes back into the foreground, it updates itself with the new data provided by the ContentProvider.

    It is hard because making a custom ContentProvider is a lot of work. It is the correct way because it is in conformance with the behavior of mobile applications and with the Android architecture: say a user activates a web-service or some computation-intensive task, and then dismisses the app; or say a push notification arrives and requires the app's data to be updated and displayed. In both cases, the app's Activitys may no longer be in the foreground, but a Service can be used to perform some non-UI operation. Now at the end of that operation, the Service makes changes to the data through the ContentProvider, and when the user activates the app again, the Activitys get their new data from the ContentProvider.

    To quote the official tutorial:

    Content providers are the standard interface that connects data in one process with code running in another process.

    As a developer, you should always assume that the user may invoke an app at any time and dismiss it at any time. Irrespective of whether an Activity is in the foreground or not, the app's data needs to be correctly updated and maintained.

    Google's own apps use custom ContentProviders. The Gmail app in particular makes use of its ContentProvider to get new emails when network connectivity is available and display emails offline. The Facebook, WhatsApp & Twitter Android apps also make use of ContentProviders.