컴퓨터/이론: 안드로이드
[2017.10.11] 43. Android 서비스(Service) 실습1 - startService
heepie
2017. 10. 11. 09:22
도입
지난번 서비스(Service) 개념 포스팅(http://heepie.tistory.com/133)에 이어 이번 포스팅에서는 서비스(Service)를 실행시키는 첫번째 방법인 startService를 실습으로 서비스(Service)의 생명주기를 확인할 예정이다.

(출처 - https://developer.android.com/guide/components/services.html?hl=ko)
실습
MainActivity
MainActivity에서는 xml에 버튼에 대한 onClick 메소드만 설정해 준다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class MainActivity extends AppCompatActivity { // 서비스를 호출하기 위한 인텐트 Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intent = new Intent(this, MyService.class); } // 서비스 시작 public void start(View v) { startService(intent); } // 서비스 종료 public void stop(View v) { stopService(intent); } } | cs |
MyService
MyService는 프로젝트 오른쪽 버튼 -> New -> Service -> Service 클릭해 기본 Service를 생성한다. 이 후 생명 주기를 확인하기 위해 메소드를 오버라이딩 했다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | public class MyService extends Service { private final String CLASSNAME = getClass().getSimpleName() + " "; public MyService() { } @Override public void onCreate() { Log.i("heepie", CLASSNAME + "onCreate"); super.onCreate(); } // 서비스의 로직은 onStartCommand에 작성 @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("heepie", CLASSNAME + "onStartCommand"); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { Log.i("heepie", CLASSNAME + "onBind"); // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } @Override public boolean onUnbind(Intent intent) { Log.i("heepie", CLASSNAME + "onUnbind"); return super.onUnbind(intent); } @Override public void onDestroy() { Log.i("heepie", CLASSNAME + "onDestory"); super.onDestroy(); } } | cs |
스크린 샷

#안드로이드 서비스 #android service #android 서비스 #android 서비스 #서비스 개념 #startService 함수 #startService 메소드