Android Application

Kotlin 브로드캐스트 리시버 : BroadCast 이벤트 송신, 수신하기

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

첨부파일

Kotlin 브로드캐스트 리시버(Broadcast Receiver,BR) : BroadCast 이벤트 송신, 수신하기
발신자와 동일한 앱에 있는 수신자에 브로드캐스트를 전송한다.
동일한 앱에서 BroadCast를 송신하고 수신을 하고 싶다면 LocalBroadcastManager를 사용한다.
앱 간에 브로드캐스트를 전송할 필요가 없을 때  LocalBroadcastManager 를 사용한다.

-------------------------------------------------------------------------------------
      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/send_broadcast"
        android:layout_width="200dp"
        android:layout_height="70dp"
        android:background="@drawable/confirm_button"
        android:text="BROADCAST 전송"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


------------------------------------------------------------------------------------
    botton_true.xml
-- res/drawable
-- New --> Drawable Resource File
-- File Name : button_true  , Root Element : shape
------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle" >
    <solid android:color="#8EC7F4" />
    <stroke android:color="#ff0000ff" android:width="4dp" />
    <padding android:left="7dp" android:top="7dp"
        android:right="7dp" android:bottom="7dp" />
    <corners
        android:radius="30dp"
        android:bottomLeftRadius="30dp"
        android:bottomRightRadius="30dp"
        android:topLeftRadius="30dp"
        android:topRightRadius="30dp" />
</shape>

------------------------------------------------------------------------------------
    botton_false.xml
-- res/drawable
-- New --> Drawable Resource File
-- File Name : button_farse  , Root Element : shape
------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle" >
    <solid android:color="#FFC107" />
    <stroke android:color="#ff0000ff" android:width="4dp" />
    <padding android:left="7dp" android:top="7dp"
        android:right="7dp" android:bottom="7dp" />
    <corners
        android:radius="30dp"
        android:bottomLeftRadius="30dp"
        android:bottomRightRadius="30dp"
        android:topLeftRadius="30dp"
        android:topRightRadius="30dp" />
</shape>

------------------------------------------------------------------------------------
    confirm_botton.xml
-- res/drawable
-- New --> Drawable Resource File
-- File Name : confirm_botton  , Root Element : selector
------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/button_false"></item>
    <item android:state_pressed="false" android:drawable="@drawable/button_true"></item>
</selector>

------------------------------------------------------------------------------------
    MainActivity.kt
------------------------------------------------------------------------------------
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val broadcaster = LocalBroadcastManager.getInstance(this)

        val send = findViewById<View>(R.id.send_broadcast) as Button

        send.setOnClickListener {
            Log.d("Tag", "클릭 실행 브로드캐스트 실행")
            val intent = Intent("MyData")
            intent.putExtra("phone", "010-1234-1111")
            broadcaster.sendBroadcast(intent)
        }
    }

    var br: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == Intent.ACTION_BATTERY_CHANGED) {
                val toast = Toast.makeText(context, "Battery status is changed.", Toast.LENGTH_LONG)
                toast.show()
            } else if (intent.action == Intent.ACTION_SCREEN_ON) {
                val toast = Toast.makeText(context, "Screen on.", Toast.LENGTH_LONG)
                toast.show()
            } else if (intent.action == "example.test.broadcast") {
                val toast = Toast.makeText(context, "Customize broadcast!", Toast.LENGTH_LONG)
                toast.show()
            }
        }
    }

    private val mMessageReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            Log.d("Tag", "커스텀 브로드캐스트 실행 받음")
            Toast.makeText(context, intent.getStringExtra("phone"), Toast.LENGTH_LONG).show()
        }
    }

    override fun onStart() {
        super.onStart()
        LocalBroadcastManager.getInstance(this).registerReceiver((mMessageReceiver),IntentFilter("MyData"))
    }

    override fun onStop() {
        super.onStop()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver)
    }

    override fun onPause() {
        super.onPause()
        unregisterReceiver(br)

    }

    override fun onResume() {
        super.onResume()
        var iFilter = IntentFilter()
        iFilter.addAction(Intent.ACTION_BATTERY_CHANGED)
        iFilter.addAction(Intent.ACTION_SCREEN_ON)
        registerReceiver(br, iFilter)
    }
}

------------------------------------------------------------------------------------
    themes.xml
------------------------------------------------------------------------------------
<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Base.Theme.BroadcastSendReceive" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">#8BC34A</item>
        <item name="colorPrimaryDark">#4B5481</item>
    </style>

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