动态注册
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
var timechange = TimeChange()
val intentFilter = IntentFilter()
intentFilter.addAction("android.intent.action.TIME_TICK")
// 添加android.intent.action.TIME_TICK的方法,系统时间变化时,会发出这个广播
registerReceiver(timechange,intentFilter)
// 注册方法
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(TimeChange())
// 一定要取消注册
}
inner class TimeChange:BroadcastReceiver(){
// 执行接受到广播之后的方法
override fun onReceive(context: Context?, intent: Intent?) {
Toast.makeText(context, "Time has changed", Toast.LENGTH_SHORT).show()
}
}
}
但是动态注册只能在程序启动之后才能执行的,因为是写在oncreate中的。如果想实现在程序未启动的时候就接收广播,需要执行静态注册。
自定义广播
标准广播
class MainActivity : AppCompatActivity() {
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
val filter = IntentFilter("com.example.myapplication.MY_BROAD")
registerReceiver(mybroad(), filter, RECEIVER_NOT_EXPORTED)
val btn:Button = findViewById(R.id.btn)
btn.setOnClickListener {
val intent = Intent("com.example.myapplication.MY_BROAD")
sendBroadcast(intent)
}
}
inner class mybroad:BroadcastReceiver(){
// 执行接受到广播之后的方法
override fun onReceive(context: Context?, intent: Intent?) {
Toast.makeText(context, "my broad", Toast.LENGTH_SHORT).show()
}
}
}
有序广播
public class MainActivity : AppCompatActivity() {
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
val btn:Button = findViewById(R.id.btn)
val filter1 = IntentFilter("com.example.myapplication.MY_BROAD")
val filter2 = IntentFilter("com.example.myapplication.MY_BROAD")
filter1.priority=1
filter2.priority=100
registerReceiver(mybroad(), filter1, RECEIVER_NOT_EXPORTED)
registerReceiver(mybroad2(), filter2, RECEIVER_NOT_EXPORTED)
btn.setOnClickListener {
val intent = Intent("com.example.myapplication.MY_BROAD")
sendBroadcast(intent)
}
}
// 定义广播接收器
public inner class mybroad:BroadcastReceiver(){
override fun onReceive(context: Context?, intent: Intent?) {
Toast.makeText(context, "my broad", Toast.LENGTH_SHORT).show()
}
}
public inner class mybroad2:BroadcastReceiver(){
override fun onReceive(context: Context?, intent: Intent?) {
Toast.makeText(context, "my broad2", Toast.LENGTH_SHORT).show()
}
}
}