Android Application

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

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

첨부파일

Kotlin 서비스(Service) : 기본 서비스
- Bound 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/bindBT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:onClick="serviceBind"
        android:text="Service Bind"
        app:layout_constraintBottom_toTopOf="@+id/unbindBT"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.207"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.877" />

    <Button
        android:id="@+id/unbindBT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="serviceUnbind"
        android:text="Sevice UnBind"
        app:layout_constraintBottom_toTopOf="@+id/callServiceBT"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.372"
        app:layout_constraintStart_toEndOf="@+id/bindBT"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.786" />

    <Button
        android:id="@+id/callServiceBT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="420dp"
        android:onClick="callServiceFunction"
        android:text="call Service Function"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        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)
    }
    // 서비스와 연결할 수 있는 서비스 커넥션 만들기
    // 만든 서비스 커넥션을 bindService() 메서드를 통해 시스템에 전달하면 서비스와 연결할 수 있음
    var myService: MyService? = null
    var isService = false
    val connection = object : ServiceConnection {
        // 서비스가 연결되면 호출된다.
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            val binder = service as MyService.MyBinder
            myService = binder.getService()
            isService = true  // onServiceDisconnected 구조에 때문에 서비스 연결 상태를 확인하는 로직이 필요
            Log.d("BoundService", "연결되었습니다.")
            //Toast.makeText(applicationContext, "연결되었습니다.", Toast.LENGTH_SHORT).show()
        }
        // 정상적으로 연결 해제되었을 때는 호출되지 않고, 비정상적으로 서비스가 종료되었을 때만 호출된다.
        override fun onServiceDisconnected(name: ComponentName) {
            isService = false
        }
    }

    fun serviceBind(view: View) {  // 버튼 이벤트
        val intent = Intent(this, MyService::class.java)
        bindService(intent, connection, Context.BIND_AUTO_CREATE)
        // 서비스를 호출하면서 커넥션을 같이 넘겨준다.
        // BIND_AUTO_CREATE : 서비스가 생성되어 있지 않으면 생성 후 바인딩을 하고 생성되어 있으면 바로 바인딩
        Toast.makeText(applicationContext, "바인드 생성.", Toast.LENGTH_SHORT).show()
    }

    fun serviceUnbind(view: View) {  // 버튼 이벤트
        if (isService) {  // 서비스가 실행되고 있을 때
            unbindService(connection)  // 바인드 해제
            Toast.makeText(applicationContext, "바인드 해제.", Toast.LENGTH_SHORT).show()
            isService = false
        }
    }

    // Bound 서비스 메세지 직접 호출
    fun callServiceFunction(view: View) {  // 버튼 이벤트
        if (isService) {
            val message = myService?.serviceMessage()  // 서비스에 있는 메서드 사용
            Toast.makeText(this, "message=${message}", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "서비스가 연결되지 않았습니다.", Toast.LENGTH_SHORT).show()
        }
    }
}

------------------------------------------------------------------------------------
*****  MyService.kt **
-- New --> Kotlin Class/File
-- Name : MyService
------------------------------------------------------------------------------------
class MyService : Service() {

    inner class MyBinder : Binder() {
        // 액티비티와 서비스가 연결되면 바인더의 getService() 메서드를 통해 서비스에 접근
        fun getService() : MyService {
            return this@MyService
        }
    }
    val binder = MyBinder()

    override fun onBind(intent: Intent): IBinder {
        return binder
    }

    // Bound 서비스 메세지 직접 호출
    fun serviceMessage() : String {
        return "서비스 Activity! 사용자 서비스 !"
    }
}

------------------------------------------------------------------------------------
    AndroidManifest.xml
------------------------------------------------------------------------------------
>>>>>  추가 하기  <<<<<<<<
    <application
            :       
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"/>
    </application>

------------------------------------------------------------------------------------
    themes.xml
------------------------------------------------------------------------------------
<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Base.Theme.BoundService" parent="Theme.AppCompat.Light">
        <item name="colorPrimaryDark">#9C27B0</item>
        <item name="colorPrimary">#FF9800</item>
    </style>

    <style name="Theme.BoundService" parent="Base.Theme.BoundService" />
</resources>