Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arranging for Android service to start again after phone restarts

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.

like image 376
Fcoder Avatar asked Jan 22 '26 06:01

Fcoder


1 Answers

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_COMPLETED

Ref: Automatically starting Services in Android after booting and Android Start Service on Boot Automatically

like image 105
Pankaj Kumar Avatar answered Jan 24 '26 21:01

Pankaj Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!