연결타입 서비스
같은 프로세스 내부 Main Thread에 서비스를 만들고 Activity와 통신
==================================================================
먼저
AndroidManifest.xml에 <service android:name=".GPService" >라고 서비스 등록.
아래와 같이 인텐트필터를 등록해도 작동한다
<intent-filter>
<action android:name="com.example.GService"/>
</intent-filter>
==================================================================
Activity에 구현할 코드
선언
private GService mGService;
private boolean mGBound = false; // 서비스와 연결된 상태를 점검
바인드를 끊을 때
if(mGSBound){
unbindService(mGConnection);
mGBound = false;
}
바인드를 연결할 때
Intent intent = new Intent(MnGAActy.this, GService.class);
bindService(intent, mGConnection, Context.BIND_AUTO_CREATE);
서버역할 중인 서비스에서 실행 결과 확인
if(mGSBound){
int intResult= mGService.getDoSomething();
String strResult= mGService.getDoSomething();
Do something what you want here!
}
서비스와 통신할 인터페이스 객체 생성
private ServiceConnection mGConnection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mGService = binder.getService();
mGBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0){
mGBound = false;
}
};
==================================================================
public class GService extends Service{
private static final String TAG = "GService";
private final IBinder mGBinder = new LocalBinder();
public class LocalBinder extends Binder{
GService getService(){
return GService.this;
}
}
public int getDoSomething(){
get result of some Processing
return result;
}
@Override
public void onCreate()
{
super.onCreate();
Log.i(TAG, "onCreate()");
}
@Override
public int onStartCommand(Intent aIntent, int aFlags, int aStartId)
{
super.onStartCommand(aIntent, aFlags, aStartId);
Log.i(TAG, "onStartCommand()");
return START_STICKY ;
}
@Override
public void onDestroy()
{
Log.i(TAG, "onDestroy()");
}
@Override
public IBinder onBind(Intent intent) {
return mGBinder;
}
}