以下是关于“Kotlin语言使用BroadcastReceiver示例介绍”的完整攻略。
什么是BroadcastReceiver?
BroadcastReceiver是一种Android组件,可以用来接收系统或应用程序发出的广播消息。广播消息是一种机制,可让应用程序在不知道其他应用程序的存在情况下相互通信。
BroadcastReceiver的注册
我们需要在AndroidManifest.xml文件中注册BroadcastReceiver,以便在系统发出广播消息时,Android系统可以找到并启动我们的BroadcastReceiver。
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
实现BroadcastReceiver
BroadcastReceiver是一个抽象类。我们需要创建一个继承BroadcastReceiver的子类,来实现我们自己的BroadcastReceiver。
class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_BOOT_COMPLETED -> {
Log.d(TAG, "Boot completed")
}
Intent.ACTION_PACKAGE_ADDED -> {
Log.d(TAG, "Package added: ${intent.data?.schemeSpecificPart}")
}
Intent.ACTION_PACKAGE_REMOVED -> {
Log.d(TAG, "Package removed: ${intent.data?.schemeSpecificPart}")
}
}
}
companion object {
const val TAG = "MyReceiver"
}
}
上面的代码演示了如何处理三个广播消息:
- Intent.ACTION_BOOT_COMPLETED:系统启动完成
- Intent.ACTION_PACKAGE_ADDED:新的应用程序已安装
- Intent.ACTION_PACKAGE_REMOVED:应用程序已被卸载
注册Receiver并监听广播
class MainActivity : AppCompatActivity() {
private lateinit var myReceiver: MyReceiver
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
myReceiver = MyReceiver()
val filter = IntentFilter().apply {
addAction(Intent.ACTION_BOOT_COMPLETED)
addAction(Intent.ACTION_PACKAGE_ADDED)
addAction(Intent.ACTION_PACKAGE_REMOVED)
addDataScheme("package")
}
registerReceiver(myReceiver, filter)
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(myReceiver)
}
}
上面的代码演示了如何在Activity中注册BroadcastReceiver,并监听特定的广播消息。
示例1:监听连接和断开网络
class NetworkReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connectivityManager.activeNetworkInfo
if (networkInfo?.isConnected == true) {
Log.i(TAG, "Network connected")
// TODO: Do something when network is connected
} else {
Log.i(TAG, "Network disconnected")
// TODO: Do something when network is disconnected
}
}
companion object {
const val TAG = "NetworkReceiver"
}
}
我们可以根据onReceive()方法的参数intent来检查广播消息的类型和内容。上面的示例演示了如何检查网络连接是否已更新。
class MainActivity : AppCompatActivity() {
private lateinit var networkReceiver: NetworkReceiver
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
networkReceiver = NetworkReceiver()
val filter = IntentFilter().apply {
addAction(ConnectivityManager.CONNECTIVITY_ACTION)
}
registerReceiver(networkReceiver, filter)
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(networkReceiver)
}
}
在Activity中注册NetworkReceiver,并监听android.net.conn.CONNECTIVITY_CHANGE广播消息。这将告诉我们Android系统是否连接了或断开了网络。
示例2:监听电池状态
class BatteryReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_BATTERY_CHANGED -> {
val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
val percentage = level * 100 / scale.toFloat()
Log.i(TAG, "Battery percentage: $percentage%")
// TODO: Do something when battery percentage changes
}
Intent.ACTION_BATTERY_LOW -> {
Log.i(TAG, "Battery is low")
// TODO: Do something when battery is low
}
Intent.ACTION_BATTERY_OKAY -> {
Log.i(TAG, "Battery is okay")
// TODO: Do something when battery is okay
}
}
}
companion object {
const val TAG = "BatteryReceiver"
}
}
上面的示例演示了如何检查电池状态的变化。
class MainActivity : AppCompatActivity() {
private lateinit var batteryReceiver: BatteryReceiver
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
batteryReceiver = BatteryReceiver()
val filter = IntentFilter().apply {
addAction(Intent.ACTION_BATTERY_CHANGED)
addAction(Intent.ACTION_BATTERY_LOW)
addAction(Intent.ACTION_BATTERY_OKAY)
}
registerReceiver(batteryReceiver, filter)
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(batteryReceiver)
}
}
在Activity中注册BatteryReceiver,并监听Intent.ACTION_BATTERY_CHANGED、Intent.ACTION_BATTERY_LOW和Intent.ACTION_BATTERY_OKAY广播消息。这将告诉我们Android系统是否已连接电源或电池电量是否已降低。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Kotlin语言使用BroadcastReceiver示例介绍 - Python技术站