Kotlin:如何在广播中获得自定义意图?



我创建的Custom Intent如下:

Intent().also { intent ->
intent.setAction("STEP_COUNT_NOTIFICATION")
intent.putExtra("stepCount", todayTotalStepCount)
sendBroadcast(intent)
}

我在AndroidManifest的Broadcast Receiver标签中添加了这个Custom Intent。

<receiver
android:name=".BroadcastReceiver.BroadcastReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_DATE_CHANGED" />
<action android:name="com.chungchunon.chunchunon_android.STEP_COUNTER_NOTIFICATION" />
</intent-filter>
</receiver>

由于我使用了两个Intent,一个是官方Intent,另一个是custom,所以我需要区分收到的Intent。

BroadcastReceiveronReceive函数

override fun onReceive(context: Context?, intent: Intent?) {
val intentAction = intent!!.action
when (intentAction) {
Intent.ACTION_DATE_CHANGED -> {
//                todayTotalStepCount = 0
var todayStepCountSet = hashMapOf<String, Int?>(
"todayStepCount" to 0
)
userDB
.document("$userId")
.set(todayStepCountSet, SetOptions.merge())
}

???? ->
}
}

我怎么能得到STEP_COUNT_NOTIFICATION这是我的自定义意图?

首先,为您的自定义action创建一个public常量:

companion object {
const val ACTION_STEP_COUNTER_NOTIFICATION = "com.chungchunon.chunchunon_android.STEP_COUNTER_NOTIFICATION"
}

对于Intent,使用相同的action:

Intent().also { intent ->
intent.setAction(ACTION_STEP_COUNTER_NOTIFICATION)
intent.putExtra("stepCount", todayTotalStepCount)
sendBroadcast(intent)
}

同样,在BroadcastReceiver:

中使用相同的action
override fun onReceive(context: Context?, intent: Intent?) {
val intentAction = intent!!.action
when (intentAction) {
Intent.ACTION_DATE_CHANGED -> {
//                todayTotalStepCount = 0
var todayStepCountSet = hashMapOf<String, Int?>(
"todayStepCount" to 0
)
userDB
.document("$userId")
.set(todayStepCountSet, SetOptions.merge())
}
// Your custom action
ACTION_STEP_COUNTER_NOTIFICATION -> { // Add your code here }
}
}
最后,对于AndroidManifest.xml:
<receiver
android:name=".BroadcastReceiver.BroadcastReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_DATE_CHANGED" />
// action should be the same as the value of ACTION_STEP_COUNTER_NOTIFICATION
<action android:name="com.chungchunon.chunchunon_android.STEP_COUNTER_NOTIFICATION" />
</intent-filter>
</receiver>

action的名称与IntentAndroidManifest.xmlBroadcastReceiver相同

您的Intent动作需要匹配相应的<intent-filter>android:name

你有:

intent.setAction("STEP_COUNT_NOTIFICATION")

有一个动作字符串STEP_COUNT_NOTIFICATION

还有:

<action android:name="com.chungchunon.chunchunon_android.STEP_COUNTER_NOTIFICATION" />

这有一个动作字符串com.chungchunon.chunchunon_android.STEP_COUNTER_NOTIFICATION

那两个不一样。它们必须相同。我建议在这两个地方都使用com.chungchunon.chunchunon_android.STEP_COUNTER_NOTIFICATION

最新更新