Android Application

Kotlin 서비스(Service) : 기본 서비스 -Start Service 예제

작성자 임베디드코리아 작성일23-10-23 23:01 조회1,397회 댓글0건

첨부파일

Kotlin 서비스(Service) : 기본 서비스
- Start Service 예제
-------------------------------------------------------------------------------------
      activity_main.xml
-------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/startBT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="76dp"
        android:onClick="serviceStart"
        android:text="Service Start"
        app:layout_constraintBottom_toTopOf="@+id/stopBT"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.469"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/stopBT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="352dp"
        android:onClick="serviceStop"
        android:text="Sevice Stop"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.458"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

------------------------------------------------------------------------------------
    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>