首先是Service的周期问题
The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called
上面是android的HP上写的关于Service周期的一段话,是说,Service在开始以后,除非调用了Context.stopService()或者stopSelf(),否则不会停止。当然如果内存不足,系统可能自动杀死Service。
下面是关于ServiceConnection接口的:
貌似现在的主流写法是这样。下面的代码的bindService method执行之后会自动调用上面ServiceConnection接口里的onServiceConnected method
有人会想,如果执行unbindService之后不就自动调用ServiceConnection接口里的onServiceDisconnected method了吗。
其实不然,查看api,你会发现,ServiceConnection接口里德onServiceDisconnected method只会在Service被停止或者被系统杀死以后调用。
The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called
上面是android的HP上写的关于Service周期的一段话,是说,Service在开始以后,除非调用了Context.stopService()或者stopSelf(),否则不会停止。当然如果内存不足,系统可能自动杀死Service。
下面是关于ServiceConnection接口的:
- private ServiceConnection conn = new ServiceConnection() {
- @Override
- public void onServiceDisconnected(ComponentName name) {
- // TODO Auto-generated method stub
- mService = null;
- }
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- // TODO Auto-generated method stub
- mService = IBindService.Stub.asInterface(service);
- }
- };
貌似现在的主流写法是这样。下面的代码的bindService method执行之后会自动调用上面ServiceConnection接口里的onServiceConnected method
- Intent intent = new Intent(IBindService.class.getName());
- bindService(intent, conn, BIND_AUTO_CREATE);
有人会想,如果执行unbindService之后不就自动调用ServiceConnection接口里的onServiceDisconnected method了吗。
其实不然,查看api,你会发现,ServiceConnection接口里德onServiceDisconnected method只会在Service被停止或者被系统杀死以后调用。
也就是说你执行unbindService 只是告诉系统你已经和这个服务没有关系了。系统在内存不足的时候可以优先杀死这个服务而已。
From: http://www.iteye.com/topic/729291
本文详细解析了Android中Service的生命周期特点,包括启动、停止及与ServiceConnection接口的交互过程。阐述了startService与stopService的区别,以及bindService的使用方式。

791

被折叠的 条评论
为什么被折叠?



