android. 간단한 Service 구현 예제

1. Service 를 구현합니다.
public class SomeService extends Service{

 public class Binder extends android.os.Binder{
  public String getMember(){
   return someMember;
  }
 }

 @Override
 public int onStartCommand( Intent intent, int flags, int startId ){
  return START_STICKY;
 }

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

 private String someMember;
 private Binder binder;

 @Override
 public void onCreate(){
  super.onCreate();

  Log.d( "TAG", "service create" );

  someMember = "Some Member";
  binder = new Binder();

 }//method

 @Override
 public void onDestroy(){

  Log.d( "TAG", "service destroy" );

  super.onDestroy();
 }
}

2. 생성한 Service 정보를 AndroidManifest.xml에 application 하위 노드로 등록합니다.
<service android:name=".SomeService" android:enabled="true"/>

3. 등록되어 사용가능해진 Service 에 바인드합니다.
private ServiceConnection sc;
private SomeService.Binder sb;

@Override
protected void onCreate( Bundle savedInstanceState ){
 super.onCreate( savedInstanceState );

 sc = new ServiceConnection(){

  @Override
  public void onServiceDisconnected( ComponentName name ){
   //According to the official document, onServiceDisconnected() would be called if the service crashed or was killed. Link
   //http://developer.android.com/reference/android/content/ServiceConnection.html
  }

  @Override
  public void onServiceConnected( ComponentName name, IBinder service ){
   sb = ( SomeService.Binder ) service;
   Log.d( "TAG", "service connect : " + sb.getMember() );
  }
 };
 getApplicationContext().bindService( new Intent( context, SomeService.class ), sc, Context.BIND_AUTO_CREATE );
}

@Override
protected void onDestroy(){

 getApplicationContext().unbindService( sc );
 super.onDestroy();

}