My question is how to create an always running background service. I created an IntentService which runs in background as long as the app is running. However, when app is killed, service is gone as well. What i want to create is to create a background service that always runs and posts notifications. (Similar to whatsapp, facebook or any other similar applications.)
When the notification is clicked, it should start the application as well.
How can i do it?
Call startService() method in Foreground Service Launcher class in your Activity to start a background service which will run forever. In order to sync something between application and server we can create a handler which run every time interval .
1: You have to invoke the service's startForeground() method within 5 seconds after starting the service. To do this, you can call startForeground() in onCreate() method of service. public class AppService extends Service { .... @Override public void onCreate() { startForeground(9999, Notification()) } .... }
For Android Developers, a Service is a component that runs on the background to perform long-running tasks. A Background Service is a service that runs only when the app is running so it'll get terminated when the app is terminated. A Foreground Service is a service that stays alive even when the app is terminated.
You must start service using start command. And you must rewrite onStartCommmand function in service:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
START_STIKY
means that service will be restarted automamtically (http://developer.android.com/reference/android/app/Service.html#START_STICKY)
If you use bindService function instead of startCommand, your service will stoped then all binded activitiess goes down.
More than that if you want to autostart your service after booting device you must implement BroadcastReceiver
for receiving ACTION_BOOT_COMPLETED
intent and handle this event for start service.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With