Android Application

Kotlin 브로드캐스트 리시버 : 배터리 상태가 변경되면 토스트 출력

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

첨부파일

Kotlin 브로드캐스트 리시버(Broadcast Receiver,BR) : 배터리의 상태가 변경 될 때 마다 토스에 출력

-------------------------------------------------------------------------------------
      activity_main.xml
-------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/ivBattery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/battery_0" />

    <EditText
        android:id="@+id/edtBattery"
        android:layout_width="match_parent"
        android:background="#87c3fa"
        android:textColor="#000000"
        android:layout_height="wrap_content" />
</LinearLayout>

------------------------------------------------------------------------------------
    MainActivity.kt
------------------------------------------------------------------------------------
class MainActivity : AppCompatActivity() {
    lateinit var ivBattery: ImageView
    lateinit var edtBattery: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        title = "배터리 상태 체크 (개선)"

        ivBattery = findViewById<ImageView>(R.id.ivBattery)
        edtBattery = findViewById<EditText>(R.id.edtBattery)
    }

    var br: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            var action = intent.action

            if (action == Intent.ACTION_BATTERY_CHANGED) {
                var remain = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
                edtBattery.setText("현재 충전량 : $remain %\n")

                if (remain >= 90)
                    ivBattery.setImageResource(R.drawable.battery_100)
                else if (remain >= 70)
                    ivBattery.setImageResource(R.drawable.battery_80)
                else if (remain >= 50)
                    ivBattery.setImageResource(R.drawable.battery_60)
                else if (remain >= 10)
                    ivBattery.setImageResource(R.drawable.battery_20)
                else
                    ivBattery.setImageResource(R.drawable.battery_0)

                var plug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0)
                when (plug) {
                    0 -> edtBattery.append("전원 연결 : 안됨\n")
                    BatteryManager.BATTERY_PLUGGED_AC -> edtBattery.append("전원 연결 : 어댑터 연결됨\n")
                    BatteryManager.BATTERY_PLUGGED_USB -> edtBattery.append("전원 연결 : USB 연결됨\n")
                }

                // 배터리 상태 출력
                var status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0)
                when (status) {
                    BatteryManager.BATTERY_STATUS_CHARGING -> Toast.makeText(applicationContext, "배터리 상태: 현재 충전중임",
                        Toast.LENGTH_SHORT).show()
                    BatteryManager.BATTERY_STATUS_NOT_CHARGING -> Toast.makeText(applicationContext,
                        "배터리 상태: 현재 충전중 아님", Toast.LENGTH_SHORT).show()
                    BatteryManager.BATTERY_STATUS_FULL -> Toast.makeText(applicationContext,
                        "배터리 상태: 충전 100% 완료", Toast.LENGTH_SHORT).show()
                    BatteryManager.BATTERY_STATUS_DISCHARGING -> Toast.makeText(applicationContext, "배터리 상태: 방전됨", Toast.LENGTH_SHORT)
                        .show()
                    else -> Toast.makeText(applicationContext,
                        "배터리 상태: 상태 알 수 없음", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}

------------------------------------------------------------------------------------
    themes.xml
------------------------------------------------------------------------------------
<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Base.Theme.BroadCastBatteryStatus" parent="Theme.AppCompat.Light">
        <!-- Customize your light theme here. -->
        <!-- <item name="colorPrimary">@color/my_light_primary</item> -->
    </style>

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