在 Android 中可以繼承 BroadcastReceiver 來處理系統事件,這裡我們註冊兩個事件:接上電源和移除電源
然後就是在 MainActivity.kt 中註冊接收器,在 registerReceiver 方法中需要傳入事件,這裡一樣填入剛剛註冊的兩個事件,然後覆寫 onDestroy 方法釋放接收器:
執行後連接電源或是移除就會看到 Toast 通知了!
參考資料:
Android Developers - BroadcastReceiver
Android Developers - Broadcasts overview
Android Developers - <receiver>
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
class MyBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_POWER_CONNECTED -> {
Toast.makeText(context, "已連接電源", Toast.LENGTH_SHORT).show()
}
Intent.ACTION_POWER_DISCONNECTED -> {
Toast.makeText(context, "已中斷電源連接", Toast.LENGTH_SHORT).show()
}
}
}
}
然後就是在 MainActivity.kt 中註冊接收器,在 registerReceiver 方法中需要傳入事件,這裡一樣填入剛剛註冊的兩個事件,然後覆寫 onDestroy 方法釋放接收器:
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
class MainActivity : ComponentActivity() {
private val receiver = MyBroadcastReceiver()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
registerReceiver(receiver, IntentFilter().apply {
addAction(Intent.ACTION_POWER_CONNECTED)
addAction(Intent.ACTION_POWER_DISCONNECTED)
})
setContent {
}
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(receiver)
}
}
執行後連接電源或是移除就會看到 Toast 通知了!
參考資料:
Android Developers - BroadcastReceiver
Android Developers - Broadcasts overview
Android Developers - <receiver>
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com