Does anyone know if there is a way of stopping an IntentService without it finishing its work thread and stopping itself?
Simple question, but I couldn't find the answer in the documentation. Is there a simple way of stopping it?
Thanks
bevor a message to a service is enqueued onStartCommand is called. which forwards the message for queueing. so you could just override onStartCommand, something like that:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals("Stop"))
stopSelf();
onStart(intent, startId);
return START_NOT_STICKY;
}
cheers
You should be able to call stopSelf();
http://developer.android.com/reference/android/app/Service.html#stopSelf()
I currently stumble upon this requierement for an app i am working on. I will try using onStartCommand to send a message to the Intent Service to stop working (for example, setup a boolean flag stopWork = true) and evaluate it during the working job or before the next queued task. The IntentService wont stop inmediately but will skip all pending tasks. Hope it helps. Gonna try it myself also.
Related
I need a service to run in background and calculate every minute distance between two locations. I used Thread in order to execute a method every minute, then I understood that when the application is closed, the service stops too since application and service use the same thread.
How can i create a simple method that is invoked every 1 minute, in background even when the application is closed?
You can run the Service in a separate process by modifying the manifest:
<service
android:name="com.example.myapplication.MyBackgroundService"
android:exported="false"
android:process=":myBackgroundServiceProcess" >
</service>
But that might not really bring any benefit. And most of the time it may even be a bad idea.
Of course the main thing is that if the Service gets shut down it's then re-started.
The Service's onStartCommand() can return the START_STICKY flag:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Other code goes here...
return START_STICKY;
}
This (and the other) options are explained in the documentation. Basically START_STICKY means "Hey Android! If you really really have to shut down my precious Service because of running low on memory, then please please try to start it again."
Whereas START_NOT_STICKY would mean "Nahh...don't bother. I'll call startService() again myself if I really need my Service running."
This (start sticky) is probably fine most of time. Your Service will just start from scratch again. You could try if that's suitable for your use case.
Then there are "foreground services" which are less likely to get shut down by Android as they are treated more like visible apps. And in fact they show up in the notification drawer with an icon and (if you make it so) a status text. So they are visible to the user like e.g. SportsTracker, Beddit and such apps.
This involves modifying your Service's onStartCommand():
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Tapping the notification will open the specified Activity.
Intent activityIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// This always shows up in the notifications area when this Service is running.
// TODO: String localization
Notification not = new Notification.Builder(this).
setContentTitle(getText(R.string.app_name)).
setContentInfo("Doing stuff in the background...").setSmallIcon(R.mipmap.ic_launcher).
setContentIntent(pendingIntent).build();
startForeground(1, not);
// Other code goes here...
return super.onStartCommand(intent, flags, startId);
}
The Service is started as usual and you can get out of the foreground mode with:
myBackgroundService.stopForeground(true);
The boolean parameters defines if the notification should also be dismissed or not.
You have to use thread for this and set a flag on starting the service. And check that flag for stoping the service.
In addition to the previous solutions provided by our friends...
MAKE SURE YOU CHECK THE "Allow background activity" BUTTON IN YOUR APP'S SETTINGS!
See the picture: In the Battery section
In my application I have an activity and a service (extends IntentService ). the service's onStartCommand looks like below
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_REDELIVER_INTENT;
}
My onHandleIntent method:
#Override
protected void onHandleIntent(Intent intent) {
while(continueLoop){ //continueLoop is controlled by the Binder
//Do stuff
}
}
I also bind to the service from activity, so I can break the infinite loop. I started the app and it's service, and then started other applications, after a while my Activity got stopped and destroyed, so is my Service. When I close the other applications using task manager , the service doesn't start by itself.
I waited and then launched my app, as soon as activity is launched service also started. I thought the android system will restart the service automatically when memory is available. Am I missing something or should i wait longer.
Thanks in advance
If you read this IntentService you'll see that
onStartCommand(Intent intent, int flags, int startId)
You should not override this method for your IntentService.
Instead
The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent).
Per the IntentService documentation:
Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
If you are binding to the Service and/or controlling the lifecycle of the service yourself, then you should use a Service and not an IntentService.
I pass through the data to be processed via intent:
Intent intent = new Intent(getActivity(), LocationService.class);
intent.putExtra....
...
startService(intent);
onCreate method called once while browsing app, but when I closed app and removed from task list(I checked, service is still runing), then I start app again - Service onCreate called again.
From the doc:
If the service is not already running, the system first calls
onCreate(), then calls onStartCommand().
Update:
What constant are you returning at the end of your onStartCommand
method?
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
Pleasee post the type of service and startmode
LocationService extends Service
Yes the android doc is correct , it will call the service's onCreate() only first time it is created , and then delivers all the intents to onStartCommand() .
But I've have came across these two google groups having the discussion that might be helpful to you
https://groups.google.com/forum/#!topic/android-developers/LtmA9xbrD5A
and https://groups.google.com/forum/#!topic/android-developers/H-DSQ4-tiac
Not much of a help , but might be of some interest .
Enjoy !
I have some tasks which is running in service. I need it to be running even if the app goes in to background. Its working fine. The problem is, How do I know When my app is removed from background?? In this scenario, I cannot stop my service and which leads to crash. Anybody please help, Thanks in advance.
I think this way you can prevent to stop background service,
In your Service class you need to return START_STICKY in onStartCommand;
Like this,
#Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
return START_STICKY;
}
If someone try to force stop service from background process, then android automatically restart your service with START_STICKY.
I hope this will help you.
I think implementing the onDestroy() method in your main class from where you are binding the Service can help
I write application which will use alarm manager. First I set up alarm manager to run some service every 20sec. Then service start some Thread. Here code of my service:
public int onStartCommand(Intent intent, int flags, int startId) {
ExtendedLog.i(TAG, "On start command");
Thread t = new Thread(wat);
t.start;
this.stopSelf();
return START_STICKY;
}
My problme is that this running properly only for few minutes. After that alarm manager starts service but thread does not start. I really dont know where is problem. Do anyone of you know what may be wrong with it? Thanks for any help.
Why are you stopping the service if you want the thread to keep running?
Looking in the Service documentation:
All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().
So since you did not stop your threads in onDestroy as requested , the system probably interrupts and stops them on its own.
What are you trying to do here? Starting a new thread & new service each 20 seconds is probably (I might even say obviously) not the best way to implement whatever you need to do... What is the code the runnable wat runs?