Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Create only one instance of Service (Android)

How can I make sure that only one instance of Service is created?

I have checked some functions with logging (WeatherService is the class who extends Service):

Log.i(TAG, "Start  Id:" + WeatherService.this.hashCode());
Log.i(TAG, "End Id:" + WeatherService.this.hashCode());

It gives different hash codes even when I am sure that the same function is running twice (downloading):

09-12 01:00:55.195: INFO/WeatherService(7222): Start  Id:1137653208
09-12 01:00:57.235: INFO/WeatherService(7222): Start  Id:1137654296
09-12 01:00:59.035: INFO/WeatherService(7222): Start  Id:1138806536
09-12 01:01:39.085: INFO/WeatherService(7222): End Id:1137654296
09-12 01:01:39.265: INFO/WeatherService(7222): Start  Id:1137654296
09-12 01:02:22.175: INFO/WeatherService(7222): End Id:1137653208
09-12 01:02:24.815: INFO/WeatherService(7222): End Id:1138806536
09-12 01:02:24.836: INFO/WeatherService(7222): Start  Id:1138806536
09-12 01:02:40.275: INFO/WeatherService(7222): End Id:1137654296

I am binding a Activity to the service with:

bindService(new Intent(getApplicationContext(),  WeatherService.class)
                               ,mServiceConnection, BIND_AUTO_CREATE);

And the service can run for minutes until it is completed, therefore the service can be binded to/created by many Activities

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

How can I make sure that only one instance of Service is created?

There can only be one instance of a given Service.

It gives different hash codes even when I am sure that the same function is running twice (downloading).

Then this is not the Service. Or, the service had been destroyed and recreated between logs.

And the service can run for minutes until it is completed, therefore the service can be binded to/created by many Activities

Then the Service is probably being destroyed and recreated. If you need the service to run for minutes, you need to use startService() and stopSelf() in addition to your bindService() and unbindService() calls. Or, perhaps you do not need to bind at all, in which case you might consider using an IntentService, since that automatically gives you a background thread on which to do your downloads.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...