Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

android - How to stop service by itself?

I start a service in an activity then I want the service to stop itself after a while.

I called stopSelf() in the service but it doesn't work.

How to make the service stop itself?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

By saying "doesn't work", I guess you mean that the onDestroy()-method of the service is not invoked.

I had the same problem, because I bound some ServiceConnection to the Service itself using the flag BIND_AUTO_CREATE. This causes the service to be kept alive until every connection is unbound.

Once I change to use no flag (zero), I had no problem killing the service by itself (stopSelf()).

Example code:

final Context appContext = context.getApplicationContext();
final Intent intent = new Intent(appContext, MusicService.class);
appContext.startService(intent);
ServiceConnection connection = new ServiceConnection() {
  // ...
};
appContext.bindService(intent, connection, 0);

Killing the service (not process):

this.stopSelf();

Hope that helped.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...