App에서 서비스 구동 방법

서비스 생성

Android Studio에서 java폴더를 우클릭해 Service를 생성한다.

Service생성

그 후 MainActivity에서 intent를 사용 서비스를 시작한다.

1
2
3
4
5
6
7
8
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Intent intent = new Intent(this, MyService.class);
startService(intent);
}

서비스 구동시 실행 동작 구현

서비스 구동시 실행 동작은 Service의 생성자에 구현하면 된다.

1
2
3
4
5
6
7
8
9
10
11
public class MyService extends Service {
public MyService() {
/* 구동시 실행 동작 구현 */
}

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
공유하기