How to start service at device boot in android?
android, android-launcher, java
Solution
First you need the permission
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
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));
}
}
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.
Problem
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?