Anand Soni
Anand Soni

Reputation: 5110

how to stop Intent services in android

i have created one intent service. Now I want to stop that service from activity how to stop that service? My code is:

MyActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {

Intent intent = new Intent(this, myService.class);
intent.putExtra("myHand", new Messenger(this.myHand)); 
startService(intent);

}

myService.java

public class myService extends IntentService {

@Override
protected void onHandleIntent(Intent intent) {

String signal = intent.getAction();
if (signal != null && signal.equals("stop")) {

stopSelf();

} else {
t.schedule(new TimerTask() {System.out.println("print")}, 0, 10000);

}

}
}

to stop service on click of button

Intent in = new Intent(this, myService.class);
in.setAction("stop");
stopService(in);

can anybody help me to stop service?

Upvotes: 1

Views: 6108

Answers (3)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

From what I know, IntentHandler creates a separate new thread, does its work, and kills itself.

So I don't think you need to explicitly stop it from an activity.

Upvotes: 0

Squonk
Squonk

Reputation: 48871

From the docs for IntentService

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. 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.

In other words, you don't have to stop an IntentService - it will terminate itself when it has no more work to do.

EDIT:

Looking back at your code, it seems you don't wan't to stop the IntentService you want to stop the TimerTask???

t.schedule(new TimerTask() {System.out.println("print")}, 0, 10000);

I don't know what t is but I'm guessing it's a Timer. If that's the case it will be running with its own Thread and attempting to terminate the IntentService is pointless - kill the Timer instead.

Also, why are you using an IntentService to create any type of object which maintains its own thread of execution?

Upvotes: 4

Simon Dorociak
Simon Dorociak

Reputation: 33495

Now I want to stop that service from activity how to stop that service?

IntentService stops itself, you shouldn't, you can't call stopSelf().

When all requests have been handled, the IntentService stops itself.

Upvotes: 2

Related Questions