ITEEDU

Service

调用者:

startService

若调用者没stopService,那Service会在后台一直运行。直到调用者再启动后stopService。

开始

Intent i = new Intent(this, TestService.class); 
this.startService(i); 

结束

Intent i = new Intent(this, TestService.class); 
this.stopService(i); 

bindService

会和调用者的生命周期绑定在一起,ServiceConnection就是起这个作用的。

开始

Intent i = new Intent(this, TestService.class);  
bindService(i, _connection, Context.BIND_AUTO_CREATE);  
_isBound = true;  

结束

if (_isBound) {  
     unbindService(_connection);  
     _isBound = false;  
}  
private ServiceConnection _connection = 
    	new ServiceConnection() {  
        public void onServiceConnected(
        		ComponentName className, IBinder service) {           
            _boundService = 
            	((TestService.LocalBinder)service).getService();  
            Toast.makeText(MainActivity.this, 
            		"Service connected",  
                    Toast.LENGTH_SHORT).show();  
        }  
        public void onServiceDisconnected(
        		ComponentName className) {  
            // unexpectedly disconnected,we should never see this happen.  
            _boundService = null;  
            Toast.makeText(MainActivity.this, 
            		"Service connected",  
                    Toast.LENGTH_SHORT).show();  
        }  
};