Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an always running background service? [duplicate]

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?

like image 531
user3686811 Avatar asked Jun 06 '14 08:06

user3686811


People also ask

How do I run background services continuously?

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 .

How do I run background service continuously in Kotlin?

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

Do services run in background?

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.


1 Answers

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.

like image 184
busylee Avatar answered Oct 21 '22 11:10

busylee