Home > Mobile >  How to call API when app state become foreground from background in android MVVM structure
How to call API when app state become foreground from background in android MVVM structure

Time:01-12

Call API when app state become foreground from background in MVVM structure in android platform.

CodePudding user response:

Foreground Services Development Let's now examine how to build a foreground service. The Service class should be extended with a new class.

The onBind() and onStartCommand() functions should be overridden. Copy the code from the BackgroundService and put it within the onStartCommand() function. Add the service to the app by going to the manifests file.

We must add the FOREGROUND SERVICE permission to the manifests file in order to make Foreground Services usable.

<uses-permission android:name=”android.permission.FOREGROUND_SERVICE”></uses-permission>
Starting the Foreground 

Starting the Foreground Service Now we need to start the service.

Go to the MainActivity file. In the onCreate() method, replace the BackgroundService class with the ForegroundService class for the intent.

Instead of calling startService(), call startForegroundService().

Intent serviceIntent = new Intent(this, MyForegroundService.class);
startForegroundService(serviceIntent);

If we run the app, the service should start. However, if we terminate the app, it will stop.

This is because we have not put the service in the Foreground yet. Calling startForegroundService() only starts the service, we still need to put it in the Foreground state.

Go back to the Foreground Service class. In the onStartCommand() method, call startForeground().

CodePudding user response:

You can use registerActivityLifecycleCallbacks to follow up the lifecycle of your app.

For example usage: https://stackoverflow.com/a/14470360/5686866

  • Related