3. Service 만들기 (2)
페이지 정보
작성자 관리자 댓글 0건 조회 4,463회 작성일 21-03-23 18:16본문
3. Service 만들기 (2)
이번에는 단순한 service 시작 어플을 만들어 보겠습니다.
1. 프로젝트 생성
프로젝트명 : ServiceTest2
2. 서비스 생성
File -> New -> Service 를 선택하여 Service를 생성한다.
Service 클래스 명 : FirstService 
class FirstService : Service() {
    override fun onBind(intent: Intent): IBinder {
        //TODO("Return the communication channel to the service.")
        throw UnsupportedOperationException("Not yet")
    }
    private var timer = Timer("TimerTest", false).schedule(2000, 3000) {
        doSomethingTimer()
    }
    // Timer에서 실행되는 함수.
    private fun doSomethingTimer(){
        Handler(Looper.getMainLooper()).post{
            Toast.makeText(applicationContext, "test", Toast.LENGTH_SHORT).show()
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        timer.cancel()
    }
    // 처음 시작되면 호출되는 함수.
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        callEvent(intent)
        return START_NOT_STICKY
    }
    // 이벤트를 호출(구현하고 싶은 코드를 구현하면 됩니다.)
    private fun callEvent(intent: Intent?){
        Log.d("My_TAG", "callEvent()")
        timer.scheduledExecutionTime()
    }
    companion object {
        fun startService(context: Context) {
            val startIntent = Intent(context, FirstService::class.java)
            context.startService(startIntent)
        }
        fun stopService(context: Context) {
            val stopIntent = Intent(context, FirstService::class.java)
            context.stopService(stopIntent)
        }
    }
}
3. 서비스 시작
파일명 : MainActivity.kt
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    override fun onResume() {
        super.onResume()
        var start_service_btn = findViewById(R.id.start_service_btn) as Button
        var stop_service_btn = findViewById(R.id.stop_service_btn) as Button
        // 서비스 시작 버튼을 눌렀을 때 이벤트 함수.
        start_service_btn.setOnClickListener {
            // 서비스를 시작하는 코드
            FirstService.startService(this)
        }
        // 서비스 종료 버튼을 눌렀을 때 이벤트 함수.
        stop_service_btn.setOnClickListener {
            // 서비스를 종료하는 코드
            FirstService.stopService(this)
        }
    }
}
레이아웃 : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/start_service_btn"
        android:text="Start Service"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/stop_service_btn"
        android:text="Stop Service"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
4. 실행
서비스 시작을 누르면 서비스가 시작되고, Service 클래스에서 Timer로 test라는 Toast를 주기적으로 띄웁니다.
그리고 서비스 종료 버튼을 누르면 서비스를 종료하고, Timer도 종료합니다.
댓글목록
등록된 댓글이 없습니다.
