Home » Android » java – Service is killed when I kill the app manually-Exceptionshub

java – Service is killed when I kill the app manually-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I’m using service to collect permanent data with my app. Even if the app is killed, I need the service to keep collecting the data.
But when I manually kill the application (from task manager I swipe the app), the service doesn’t restart.

Here is my code :

public class ServiceAlarm extends Service {
private final LocalBinder mBinder = new LocalBinder();


public class LocalBinder extends Binder
{
    public ServiceAlarm getService()
    {
        return ServiceAlarm.this;
    }
}

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

@Override
public void onCreate() {
    super.onCreate();

}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.i("CheckLo", "Destroyed");
//NOT WORKING !!! It doesn't restart the service
    Intent intent = new Intent(this, ServiceAlarm.class);
    startService(intent);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            StartESP();
        }
    });

    return android.app.Service.START_STICKY;
}
public void StartESP()
{
    Thread welcomeThread = new Thread() {
        @Override
        public void run() {
            try {

                super.run();
                sleep(5000);  //Delay of 10 seconds
            } catch (Exception e) {

            } finally {

                //Do some task
                Log.i("CheckLo", "Started");
                StartESP();

            }
        }
    };
    welcomeThread.start();
}

}

I call it like this :

    Intent intent = new Intent(this, ServiceAlarm.class);
    startService(intent);

and in manifest :

  <service
        android:name=".Alarm.ServiceAlarm"
        android:stopWithTask="false"
        android:enabled="true">
    </service>

If anyone has solution, please let me know

How to&Answers: