context.sendBroadcast(intent)
通常會伴隨資料的傳遞intent.putExtra()
context.sendOrderBroadCast(intent)
這個在intent-filter中設定優先順序android:priority
在Androidmanifest.xml中註冊
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="com.example.broadcast" />
</intent-filter>
</receiver>
建立一個BroadCasteReceiver的子類的範例化物件
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="com.example.broadcast" />
</intent-filter>
</receiver>
//1.建立一個物件
final MyReceiver myReceiver2 = new MyReceiver();
//2.設定button入口,設定事件監聽
Button btn_register = findViewById(R.id.register_broadcast);
btn_register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//新增一個Intentfilter物件,新增action屬性
IntentFilter filter = new IntentFilter();
filter.addAction("MyReceiver2");
//將intentfilter與建立的子類物件關聯起來
registerReceiver(myReceiver2,filter);
}
});
Button btn_unregister = findViewById(R.id.unregister_broadcast);
btn_unregister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
unregisterReceiver(myReceiver2);
}
});