目录
6.3 发送自定义广播
现在你已经学会了通过 BroadcastReceiver 来接收系统广播,接下来我们就要学习一下如何在应用程序中发送自定义的广播。前面已经介绍过了,广播主要分为两种类型:标准广播和有序 广播。本节我们就通过实践的方式来看一下这两种广播具体的区别。
6.3.1 发送标准广播
在发送广播之前,我们还是需要先定义一个 BroadcastReceiver 来准备接收此广播,不然发出去也是白发。因此新建一个 MyBroadcastReceiver ,并在 onReceive() 方法中加入如下代 码:
class MyBroadcastReceiver : BroadcastReceiver(){
override fun onReceive(context: Context?, intent: Intent?) {
Toast.makeText(context, "received in MyBroadcastReceiver",
Toast.LENGTH_SHORT).show()
}
}
当 MyBroadcastReceiver 收到自定义的广播时,就会弹出 “received in MyBroadcastReceiver ”的提示。
然后在AndroidManifest.xml 中对这个BroadcastReceiver 进行修改:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.broadcasttest">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
androi