I am starting a service from my main Android activity as follows:
final Context context = base.getApplicationContext();
final Intent intent = new Intent(context, MyService.class);
startService(intent);
When I close the activity page by swiping it out from the recent apps list, the service stops running and restarts after some time. I can't use persistent services with notifications because of my app requirements. How can I make the service NOT restart or shutdown and just keep on running on app exit?
try this, it will keep the service running in the background.
BackServices.class
in your MainActivity
onCreate
drop this line of codeNow the service will stay running in background.
make you service like this in your Mainifest
then your service will run on other process named ServiceProcess
if you want make your service never die :
onStartCommand() return START_STICKY
onDestroy() -> startself
create a Deamon service
jin -> create a Native Deamon process, you can find some open-source projects on github
startForeground() , there is a way to startForeground without Notification ,google it
This may help you. I may be mistaken but it seems to me that this is related with returning
START_STICKY
in youronStartCommand()
method. You can avoid the service from being called again by returningSTART_NOT_STICKY
instead.You must add this code in your Service class so that it handles the case when your process is being killed
The Main problem in unable to start the service when app closed,android OS(In Some OS) will kill the service for Resource Optimization, If you are not able to restart the service then call a alarm manger to start the reciver like this,Here is the entire code,This code will keep alive ur service.
Manifest is,
IN Main Activty start alarm manger in this way,
this will call reciver and reciver is,
And this Alaram reciver calls once when android app is opened and when app is closed.SO the service is like this,
Just override onDestroy method in your first visible activity like after splash you have home page and while redirecting from splash to home page you have already finish splash. so put on destroy in home page. and stop service in that method.