BroadcastReceiver(廣播接收器)是應用程式元件之一,類似於訂閱與發布的設計模式,分為Broadcaster(廣播器)與Receiver(接收器),廣波器可發送自定義或系統預設的廣播事件,讓接收器取得訊息,而接受器則註冊特定的頻道,等待廣播器發送訊息並執行對應的處理。
File→New→Other→Broadcast Receiver
修改Receiver名稱後點選Finish
AS會自動產生BroadcastReceiver需要的檔案,AndroidManifest.xml也會自動增加Receiver的資訊
在Activity中建立BroadcastReceiver物件,就不必在AndroidManifest.xml新增Receiver標籤
private val receiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
intent.extras?.let {
//...下略
}
}
}
//註冊
registerReceiver(receiver, IntentFilter("MyBroadcast"))
//註銷
unregisterReceiver(receiver)
Receiver註冊時,需使用IntentFilter類別定義要接收的事件,而Broadcaster在發送前,也必須定義事件的「識別標籤」,識別標籤會決定要接收的事件類型,而廣播事件的類型分為系統預設與自行定義。
class MainActivity : AppCompatActivity() {
//實作當螢幕開啟時顯示螢幕開啟的Toast
//Step1:建立BroadcastReceiver物件
private val receiver = object : BroadcastReceiver() {
//Step2:在onReceive()中加入接收廣播後要執行的動作
override fun onReceive(context: Context, intent: Intent) {
//用Toast顯示通知訊息
Toast.makeText(context, "螢幕開啟", Toast.LENGTH_SHORT).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Step3:建立IntentFilter物件,並指定接收的識別標籤為螢幕開啟
val intentFilter = IntentFilter(Intent.ACTION_SCREEN_ON)
//Step4:註冊Receiver
registerReceiver(receiver,intentFilter)
}
}
class MainActivity : AppCompatActivity() {
//Step1:建立BroadcastReceiver物件
private val receiver = object : BroadcastReceiver() {
//Step2:在onReceive()中加入接收廣播後要執行的動作
override fun onReceive(context: Context, intent: Intent) {
intent.extras?.let {
//解析intent取得字串訊息
val msg = "資料:${it.getString("msg")}"
Toast.makeText(context, "螢幕開啟", Toast.LENGTH_SHORT).show()
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Step3:建立IntentFilter物件,並指定接收的識別標籤為MyBroadcast
val intentFilter = IntentFilter("MyBroadcast")
//Step4:註冊Receiver
registerReceiver(receiver,intentFilter)
}
}
由於是自定義的事件,因此需要應用程式執行sendBroadcast(),來發送廣播讓Receiver接收。通常會撰寫在其他程式區塊
//建立帶有識別標籤的Intent
val intent = Intent("MyBroadcast")
//發送自定義的廣播事件
sendBroadcast(intent.putExtra("msg","data")