3

I am making an app which needs a service running at all times, even when the app is closed, from device boot to device shutdown. Can this be done in android?

vergil corleone
  • 1,091
  • 3
  • 16
  • 34

1 Answers1

10
  1. First you need the permission

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    
  2. Then create a Broadcast receiver as

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    
    public class Startup extends BroadcastReceiver {
    
        public Startup() {
        }
    
        @Override
        public void onReceive(Context context, Intent intent) {
            // start your service here
            context.startService(new Intent(context, SERVICE.class));
        }
    
    }
    
  3. Register this BroadCast Receiver in your manifest as

    <receiver android:name="YOUR_PACKAGE.Startup" >
        <!-- This intent filter receives the boot completed event -->
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    

Note: A service too is not guaranteed to run from device boot to device shut down, as in extreme cases the Android system may kill the service also to gain additional memory.

Rachit Mishra
  • 6,101
  • 4
  • 30
  • 51
  • It is very important for the app user that the service stay alive always. Is there a way to make sure android doesn't kill the service unless its under extreme load? – vergil corleone Dec 15 '13 at 14:14
  • Use an `IntentService` service, which will be restarted if the Service is killed while handling the intent, I haven't come up with other methods yet. – Rachit Mishra Dec 15 '13 at 14:23
  • @twntee dont agree. IntentService is supposed to stop after running once, so its not going to run all the time. – Utsav Gupta Sep 02 '14 at 10:15
  • @user2103379 In certain case when your IntentService is performing long operation, and system needs to free up memory, it will get killed. – Rachit Mishra Sep 07 '14 at 20:37
  • Try adding android:enabled="true" to the receiver delcalration in manifest. – berserk Mar 04 '15 at 09:43
  • `context.startService(new Intent(context, SERVICE.class));` will throw an IllegalStateExeption for Android versions >= Oreo because you can not anymore start a service if app is in background. Check this https://medium.com/@berriz_/service-and-boot-completed-on-android-o-6a389eae50f1 – Fivos Apr 11 '19 at 11:10