i need a service in my app that starts first time and runs forever, even if user restart his phone, my service starts automatically without running my app. i write this code but when user restart his phone, my service doesn't start again!!
public class notifService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStart(intent, startId);
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
and in the main activity i start service like this:
// start service
Intent service = new Intent(MainActivity.this, notifService.class);
MainActivity.this.startService(service);
thanks for you help.
Listen for android.intent.action.BOOT_COMPLETED in BroadcastReceiver and start your service.
For example
public class YourDefinedBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, notifService.class);
context.startService(service);
}
}
Also, you must hold the permission:
RECEIVE_BOOT_COMPLETEDRef: Automatically starting Services in Android after booting and Android Start Service on Boot Automatically
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