W.A 저장소

Service 본문

카테고리 없음

Service

W.A 2010. 8. 23. 12:01
비활성 엑티비티보다 높은 우선순위를 가짐
서비스가 종료되어도 리소스가 충분해지면 즉시 재시작
Activity, Broadcast receiver와 같이 어플리케이션 프로세스의 메인 쓰레드 내에서 실행.

백그라운드 작업 수행
IPC(Inter-Process Communication)를 위한 원격접속 가능한 오브젝트를 만들어내는 것

서비스 라이프사이클(두가지 용도)
시작(startService()) -> onCreate -> onStart -> run -> onDestroy
시작(bindService()) -> onCreate -> onBind -> run -> onUnbind -> onDestroy
                                                            onRebind

서비스 등록
암시적
startService(new Intent(MyService.MY_ACTION));
명시적
startService(new Intent(this, MyService.class));

서비스 중지

ComponentName service = startService(new Intent(this, BaseballWatch.class));

stopService(new Intent(this, service.getClass()));
명시적 중단
try {
Class serviceClass = Class.forName(service.getClassName());
stopService(new Intent(this, serviceClass));
}catch(ClassNotFountException e) {}

입력 이벤트에 대해 5초 이내, onReceive 핸들러를 10초 이내에 완료하지 않으면 Application Unresponsive메시지가 나옴.
(위와 같은 상황이 있으면 쓰레드를 사용해야함.)

// 이메쏘드는메인GUI 쓰레드에서호출된다.
private void mainProcessing() {
// 이는시갂이맋이드는작업을자식쓰레드로옮긴다.
Thread thread= newThread(null, doBackgroundThreadProcessing, "Background");
thread.start();
}
// 백그라운드처리메쏘드를실행하는Runnable
private Runnable doBackgroundThreadProcessing = new Runnable() {
public void run() {
backgroundThreadProcessing();
}
};
// 백그라운드에서몇가지처리를수행하는메쏘드
private void backgroundThreadProcessing() {
[ ... 시간소모적인작업들... ]
}

핸들러
두가지 방법
메시지 객체를 만들어서 메인쓰레드에 알려주는 방법
Message는send로,runnable객체는post로전달함

// 메인쓰레드에서핸들러를초기화한다.
private Handler handler= new Handler();
private void main Processing() {
// 이는시간이맋이드는작업을자식쓰레드로옮긴다.
Thread thread= newThread(null, doBackgroundThreadProcessing, "Background");
thread.start();
}
// 백그라운드처리메쏘드를실행하는Runnable
private Runnable doBackgroundThreadProcessing = new Runnable() {
public void run() {
backgroundThreadProcessing();
}
};
// 백그라운드에서몇가지처리를수행하는메쏘드
private void backgroundThreadProcessing() {
[ ... 시갂소모적인작업들... ]
handler.post(doUpdateGUI);
}
// GUI 업데이트메쏘드를실행하는Runnable
private Runnable doUpdateGUI = new Runnable{
public void run() {
updateGUI();
}
};
private void updateGUI() {
[ ... 다이얼로그를오픈하거나GUI 요소를수정할수있다... ]
}