Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping an IntentService from an activity

I have an IntentSerivce that runs in the background sometimes and it can be quite a long running process in certain instances. I give an option for the user to quit the application which basically just stops and polling and ignores any GCM push notifications. But if a push notification came in and the IntentService is taking a while to finish doing what it has to (gets information from a server and sends a notification to the user if needed, like a new message arrived or something).

Here is the problem, if the user elects to "Quit" the app while the intentservice is still running they will still get the notification which I do not want. I know that there is the stopSelf() method for the service but I need to stop it in an activity when I know the user "Quit" the application via a menu button. Sending another intent to the service does not work since the intents get queued up and calling context.stopService(intent); in my activity does not work either so how else can I stop it?

like image 575
tyczj Avatar asked Aug 24 '12 16:08

tyczj


People also ask

How do I disable IntentService?

When user call startService() from activity, it doesn't create the instance for each request and it going to stop service after done some action in service class or else we need to stop service manually by using stopSelf(). This example demonstrates about Android stop specified IntentService.

Does IntentService run on background thread?

The IntentService class provides a straightforward structure for running an operation on a single background thread. This allows it to handle long-running operations without affecting your user interface's responsiveness.

Why IntentService is deprecated?

Provided since Android API 3, the purpose of IntentService was to allow asynchronous tasks to be performed without blocking the main thread. The deprecation is one of a number of steps introduced starting with Android 8.0 (API 26) to limit the actions that can be performed while an app is in the background.


2 Answers

Are you passing a new Intent into stopService(Intent) or the original one used in startService(Intent). Passing the original Intent should stop the service.

Failing that you could use a Handler to pass the service a Message. Have the IntentService implement the Handler.Callback interface and create a new Handler(Handler.Callback) in your Activity, passing your IntentService as callback. Then implement the onHandleMessage() in your IntentService to call stopSelf() and have your Activity pass a message to it when you want it to stop.

like image 159
bennettaur Avatar answered Oct 17 '22 05:10

bennettaur


Below code is perfectly working fine for me to stop IntentService from Activity:

stopService(new Intent(getApplicationContext(), MyIntentService.class));
like image 35
Vikasdeep Singh Avatar answered Oct 17 '22 06:10

Vikasdeep Singh