When you start an android service in activity, the service runs in the activity main thread. If the service is time consuming, then the main thread will be blocked. So we had better start a child thread in the service object, this can make your activity execute smoothly.
Android foreground service is an android service object. But it always run in foreground, this can avoid service object being recycled by android system when android os do not have enough resources. Android foreground service can be interacted by user through notification. It is generally used in music player, file downloader etc.
To start an android background service when device boot, you should create a broadcast receiver, and make it listen android.intent.action.BOOT_COMPLETED action. Then in the custom broadcast receiver’s onReceive method, you can start the background service.
This article will show you how to communicate between activity and background service in android. It will play, pause and stop a web audio file in android background service in this example. It will also update activity progress bar from background service to display audio playing process.
Android service is a very important component in android app development. It is generally run in background. It do not has user interface. If you start it in activity then it is run in the activity main thread. So when the activity is destroyed, the background service started in it is destroyed also.
This example will show you how to implement force logout when same user account login in another instance of same android app. It will use both android activity, service and broadcast receiver components to implement.
In some cases, you may need to create a broadcast receiver which can still run at the background after the android app exit. This example will just tell you how to do that use broadcast receiver and android service object.