Service Bind



Service Bind  란,

클라이언트 - 서버 인터페이스 안의 서버를 말합니다.

쉽게 말해, Service 가 일종의 서버가 되어서 클래스에서 요청을 하면 응답을 해준다 라고 보시면 됩니다.


바인드된 서비스는, 애플리케이션이 종료되면 없어집니다.

따라서, 계속해서 사용하지 않는 서비스는 이것을 이용하면 효율적이라 생각이 됩니다.




Bind


바인드된 서비스를 이용하려면 onBind() 메서드를 오버라이드 해야 합니다.

이를 통해, 다른 애플리케이션이 이 서비스에 바인드 하여 상호작용 할 수 있습니다.


LocalBinder 클래스 의 getService() 함수를 통해 Binder 에 접근 할 수 있습니다.


public class LocalService extends Service {
   
// Binder given to clients
   
private final IBinder mBinder = new LocalBinder();
   
// Random number generator
   
private final Random mGenerator = new Random();

   
/**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */

   
public class LocalBinder extends Binder {
       
LocalService getService() {
           
// Return this instance of LocalService so clients can call public methods
           
return LocalService.this;
       
}
   
}

   
@Override
   
public IBinder onBind(Intent intent) {
       
return mBinder;
   
}

   
/** method for clients */
   
public int getRandomNumber() {
     
return mGenerator.nextInt(100);
   
}
}


주목해야 할 것은 LocalBinder 클래스와 onBind 에 바인드된 iBinder

그리고, public 으로 선언된 getRandomNumber() 함수 입니다.

Binder 를 통해 위 함수에 접근 할 수 있는 것이죠.





Call Bind Service


ServiceConnection 을 통해 서비스객체에 접근 합니다.


public class BindingActivity extends Activity {
   
LocalService mService;
   
boolean mBound = false;

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView
(R.layout.main);
   
}

   
@Override
   
protected void onStart() {
       
super.onStart();
       
// Bind to LocalService
       
Intent intent = new Intent(this, LocalService.class);
        bindService
(intent, mConnection, Context.BIND_AUTO_CREATE);
   
}

   
@Override
   
protected void onStop() {
       
super.onStop();
       
// Unbind from the service
       
if (mBound) {
            unbindService
(mConnection);
            mBound
= false;
       
}
   
}

   
/** Called when a button is clicked (the button in the layout file attaches to
      * this method with the android:onClick attribute) */

   
public void onButtonClick(View v) {
       
if (mBound) {
           
// Call a method from the LocalService.
           
// However, if this call were something that might hang, then this request should
           
// occur in a separate thread to avoid slowing down the activity performance.
           
int num = mService.getRandomNumber();
           
Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
       
}
   
}

   
/** Defines callbacks for service binding, passed to bindService() */
   
private ServiceConnection mConnection = new ServiceConnection() {

       
@Override
       
public void onServiceConnected(ComponentName className,
               
IBinder service) {
           
// We've bound to LocalService, cast the IBinder and get LocalService instance
           
LocalBinder binder = (LocalBinder) service;
            mService
= binder.getService();
            mBound
= true;
       
}

       
@Override
       
public void onServiceDisconnected(ComponentName arg0) {
            mBound
= false;
       
}
   
};
}


ServiceConnection 으로 Binder 를 가져와서 Service 객체를 얻어옵니다.

mService 객체를 통해 public 함수인 getRandomNumber () 를 가져올 수 있습니다.






출처 : https://developer.android.com/guide/components/bound-services.html?hl=ko#Binder

Posted by 자바리즘
,