------------------------------------------------------------------------------------
MainActivity.kt
------------------------------------------------------------------------------------
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
// Started 서비스 실행
fun serviceStart(view: View) { // 버튼 이벤트
val intent = Intent(this, MyService::class.java)
intent.action = MyService.ACTION_START // 넘겨줄 인텐트 액션 설정
startService(intent)
}
// Started 서비스 종료
fun serviceStop(view: View) { // 버튼 이벤트
val intent = Intent(this, MyService::class.java)
//intent.action = MyService.ACTION_STOP
//startService(intent)
stopService(intent)
}
}
------------------------------------------------------------------------------------
***** MyService.kt **
-- New --> Kotlin Class/File
-- Name : MyService
------------------------------------------------------------------------------------
class MyService : Service(){
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val action = intent?.action // 넘어오는 인텐트의 액션
Log.d("StartedService", "action=$action")
Toast.makeText(applicationContext, "action=$action", Toast.LENGTH_SHORT).show()
return super.onStartCommand(intent, flags, startId)
}
// Started 서비스 종료 확인
override fun onDestroy() {
Log.d("Service", "서비스가 종료되었습니다.")
Toast.makeText(applicationContext, "서비스가 종료되었습니다.", Toast.LENGTH_SHORT).show()
super.onDestroy()
}
override fun onBind(intent: Intent?): IBinder? {
TODO("Not yet implemented")
}
companion object {
// 명령어 작성 : "패키지명 + 명령어"
val ACTION_START = "ek.example.servicebasekotlin.START"
val ACTION_RUN = "ek.example.servicebasekotlin.RUN"
val ACTION_STOP = "ek.example.servicebasekotlin.STOP"
}
}
------------------------------------------------------------------------------------
AndroidManifest.xml
------------------------------------------------------------------------------------
>> 추가 하기 <<
<application
:
<service android:name=".MyService"/>
<activity
android:name=".MainActivity"
:
</activity>
</application>