Service Example
background daemon 방식의 서비스 예제이다. 웹 서핑과 음악 감상을 동시에 하는 앱을 만들고자 한다면 백그라운드 서비스를 통해 음악을 재생하면 된다.
하기 예제는 서비스를 실행하면 핸들러에 의해서 1초 단위로 run() 함수가 실행된다. 마지막 run() 호출 후 1초 이내에 서비스를 종료하면 onDestroy()가 호출되어 mIsRunning이 false가 된다. 서비스를 manifest에 추가해주는 것도 잊지말자.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> </manifest> |
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" |
MainActivity.java
package com.serviceexmaple.mystoryg.serviceexample;
|
MyService.class
package com.serviceexmaple.mystoryg.serviceexample; } |
실행 결과 log
12-17 17:24:34.700 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN 12-17 17:24:34.789 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP 12-17 17:24:34.794 11136-11136/com.serviceexmaple.mystoryg.serviceexample D/MainActivity: mServiceName = ComponentInfo{com.serviceexmaple.mystoryg.serviceexample/com.serviceexmaple.mystoryg.serviceexample.MyService} 12-17 17:24:34.795 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: onCreate() 12-17 17:24:34.807 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: startId = 1 12-17 17:24:35.810 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run() 12-17 17:24:36.812 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run() 12-17 17:24:37.814 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run() 12-17 17:24:38.816 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run() 12-17 17:24:39.819 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run() 12-17 17:24:40.345 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN 12-17 17:24:40.453 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP 12-17 17:24:40.459 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: onDestroy() 12-17 17:24:40.820 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: It run after call onDestroy() |
'프로그래밍 > Android' 카테고리의 다른 글
알람 예제 (AlarmManager Example) (0) | 2016.12.22 |
---|---|
브로드캐스트 리시버 (BroadcastReceiver Example) (0) | 2016.12.20 |
알림 예제(Notification Example) (0) | 2016.12.20 |
명시적 인텐트(Explicit Intent) (0) | 2016.12.16 |
암시적 인텐트(Implicit Intent) (0) | 2016.12.15 |
WebView 줄바꿈 문제 (0) | 2016.02.18 |
이클립스 Java was started but returned exit code=13 오류 (0) | 2015.07.19 |