简体   繁体   中英

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

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

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().

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM