I am making an app that gives the user a notification when it is time for a monster egg to be hatched again. Up to 10 eggs can be hatched per day every 5 minutes. I thought I'd make a service that keeps a track of how much time has passed, but every time MainActivity closes on the emulator the service stops and calls onDestroy(). I made a test service to see if I could get the service to display log messages, or do something when onDestroy() is called. I was able to get the service to run a thread in onDestroy(), but obviously this is dangerous if I were to implement it.
I was also reading around the site and notice people recommend either Handler or Alarm Manager. Should I use these instead of service? And could someone also explain why my service stops when MainActivity is destroyed? Also would it be recommended to retrieve/store data from app preferences within this service or whatever class I end up using so that the service and MainActivity can talk to each other? Like for example a seed based on whenever the timer is up so that MainActivity can create an egg from the seed whenever it is started?
(edit)oops almost forgot: I also need it so that notifications appear whenever an egg is ready to hatch and whenever another batch of eggs is ready for the day. Whenever the user starts the app, the app should also display how long is left for another egg or another batch if the user has already used up their eggs for the day. Figured this context was important in determining whether I should use a service, alarm manager, or handler.
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
public class egg_notifications extends Service {
public static int time = -1;
public egg_notifications() {
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
AsyncTask datatask = new AsyncTask() {
@Override
protected Object doInBackground(Object[] objects) {
for(int c=0;c<300;c++){
Log.i("d","Time is "+c);
try {
Thread.sleep(1000);
} catch (Exception e) { }
}
return null;
}
}.execute();
return Service.START_STICKY;
}
@Override
public void onDestroy() {
Log.i("d","Service onDestroy");
AsyncTask datatask = new AsyncTask() {
@Override
protected Object doInBackground(Object[] objects) {
for(int c=0;c<300;c++){
Log.i("d","Time is "+c);
try {
Thread.sleep(1000);
} catch (Exception e) { }
}
return null;
}
}.execute();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}