如何确保只创建一个Service实例?
我已经使用日志记录了一些函数(WeatherService是扩展Service的类):
Log.i(TAG, "Start Id:" + WeatherService.this.hashCode());
Log.i(TAG, "End Id:" + WeatherService.this.hashCode());
即使我确定相同的函数运行两次(下载),它也会给出不同的哈希码:
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
我正在使用以下代码将Activity与服务绑定:
bindService(new Intent(getApplicationContext(), WeatherService.class)
,mServiceConnection, BIND_AUTO_CREATE);
服务可以运行数分钟直至完成,因此该服务可以绑定/由多个Activity创建。