Search code examples
javaandroidserviceondestroy

How to prevent the service from being destroyed when I exit the app


I have a service class that reads from firebase and sends the readings to the model to get the response. But, the problem is that the service is destroyed when I exit the app.

Notes:

  1. my service starts when I login and must destroyed when I log out in the app
  2. my service class contains broadcast receiver as an inner class to show a dialog in case I get the desired response from the model to show a custom dialog.

^ this note written in case it is important

I looked for the already asked questions, no one solved my issue.

I have to let the Service run when I exit the app

Manifest file:

<service android:name=".ModelServiceM"
android:enabled="true"
android:exported="false" />

Service class:

public class ModelServiceM extends Service {
    
    Timer timer = new Timer();
    BroadcastReceiver mReceiver;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
      //skip this for now
        /*IntentFilter filter = new IntentFilter();
        filter.addAction("action");
        mReceiver = new MyReceiver();
        registerReceiver(mReceiver, filter);*/
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d("message","onStartCommand Lunched");
        //things

            timer.schedule(new TimerTask() {
                public void run() {
                  
                  //things 
            }, delay,period);


    //return START_STICKY;
        flags=START_STICKY;
    return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onDestroy() {
        Log.d("message","onDestroy Lunched");
        timer.cancel();
        //unregisterReceiver(mReceiver);
        super.onDestroy(); } 


    // use this as an inner class like here or as a top-level class
    public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // do something
            Log.d("RECEIVER","onReceive lunched");
            //things
        }
        // constructor
        public MyReceiver(){ }
    }
}

Solution

  • Take a look at ForegroundServices they live even if app is closed.