개발 공부/안드로이드
[Service] 서비스 기본 개념
Dev.Jun
2017. 6. 21. 08:04
서비스
1. 서비스란
백그라운드에서 실행되는 프로세스
- 화면이 없는 액티비티
-
AndroidManifest.xml
에<service>
로 명시되어 있어야 서비스가 정상 작동한다. - 프로세스 분리가 아닌 기존 프로세스에서 돌아간다. 이런 이유로 thread에서 별도로 처리한다고 생각할 수도 있는데 그것도 아니다.
2. 서비스 생명주기
서비스의 생명주기는
onCreate()
,onStartCommand()
,onDestroy()
크게 세 단계를 거친다.
3. 서비스의 구현
-
MainAcitivty.class
에서 특정 메소드 호출 시,service
호출한다. -
Activity, Broadcast Receiver, Service, Content Provide와 같은 컴포넌트 간의 통신은
Intent
객체가 메신저 역할을 한다.
public class MainActivity extends AppCompatActivity {
Intent service;
@Override
public void playerPlayer() {
// 1. 서비스를 생성한다.
// Intent 객체인 `service`에 명령어를 담아 넘긴다.
service.setAction(Const.Action.PLAY)
startService(service);
}
}
public class PlayerService extends Service {
@Overrride
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
// 인텐트를 통해 전달받은 명령어를 꺼낸다.
String action = intent.getAction();
switch (action) {
case Const.Action.PLAY:
playerStart();
break;
case Const.Action.PAUSE:
Player.pause();
break;
case Const.Action.STOP:
stopService();
break;
}
}
return super.onStartCommand(intent, flags, startId);
}
}
}