App Reload in Ionic 3

Easily manage your app’s lifecycle with a service

Valentin Klinghammer
prototype.berlin

--

Problem

Newer mobile devices have more and more memory and use that memory more efficiently. That means, the operating system can keep apps longer active than anticipated. This may lead to weird behavior or stale states within the app, e.g. some content not refreshing after a few days.

Solution

We want the app to hard reload after a certain amount of time, to ensure a fresh app state when the user is more than likely to have forgotten about the app.

Implementation

1. Save a timestamp of the current datetime

First, we create a service and add a public method called init. That method will be called from our app.component to initialize the behavior.

We’re using our localStorage service from our previous blog post about an Ionic 3 localStorage Service.

2. Add a resume callback to refresh if necessary

We’re using the Ionic Platform provider to subscribe to the resume event. We then retrieve the timestamp from step 1 when the app resumes and check, wether it crossed our threshold.

If it did cross it, we show the splash screen and do a hard reload.

We’re using our Constants Provider on which we’ll do a separate blog post, C.appReloadThreshold simply contains the threshold in milliseconds after which to reload, e.g. 20*60*60*1000 for 20 minutes.

3. Add AppReloadService.init to app.component

Now, simply find a place in your app.component to call the init method. There’s usually a lot going on in the app.component of a typical project, but for the AppReloadService it doesn’t really matter.

Improvements

It might make sense to save the time only when actually being put into the background. The way it’s currently implemented may surprise the user who has been using the app for 2 hours and then just quickly switches between apps only to find his data gone.

I hope, this helps someone!

Here’s the code of the complete service for easy reference:

--

--