Local Service를 이용해보자!

Mobile Programming/Android 2011. 1. 18. 18:46
서비스는 백그라운드에서 네트워크를 통해 어떤 파일을 다운받는다거나 ,  음악을 플레이 한다거나등의 작업을 하는 컴포넌트이다.

먼저 액티비티와 같이 Manifest 에 정의해주고 , 

1 . 액티비티에서 서비스 클래스를 실행시키고 ( startService )
2 . bindService 의 두번째 인자에 해당하는 ServiceConnection의 객체를 생성하고 onServiceConnected에 필요한 작업을 구현한다.
3 . 바인드 요청을 위해 bindService 메서드를 호출한다.
4 . 바인드 요청을 받을 서비스 클래스는 onBind 를 구현한다.
5 .  onBind의 리턴값은 액티비티와 통신을 할 IBinder를 상속한 클래스의 객체이다 . 따라서 그 객체를 구현해 줄 필요가 있다.
6 . 객체를 리턴한다.

코드로 확인해보기 바란다.

먼저 액티비티이다. (클래스 명이 헷갈리게 명명된 점 양해부탁드립니다.)


 
public class LocalService extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ServiceConnection tserviceConnection = new ServiceConnection(){

			public void onServiceConnected(ComponentName name, IBinder service) {
				// TODO Auto-generated method stub
				Log.d("localservice","connected");
				((Service.TempBinder)service).sayHello();
			}

			public void onServiceDisconnected(ComponentName name) {
				// TODO Auto-generated method stub
				
			}
        	
        };
        
        startService(new Intent(LocalService.this, Service.class));
        
        bindService(new Intent(LocalService.this, Service.class),tserviceConnection,0);
    }
}
다음은 서비스클래스이다.
public class Service extends android.app.Service {

	class TempBinder extends Binder{
		public void sayHello(){
			Log.d("localservice","hello");
		}
	}
	
	TempBinder tb = new TempBinder();
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return tb;
	}

}