我想发送广播消息并在BroadcastReceiver
中抓住它。
这是我发送消息的方式:
override fun addToSchedule(event: EntityObject) {
val pendingIntent = createEventPushPendingIntent(event)
alarmManager.set(AlarmManager.RTC_WAKEUP, computeTimeToPush(event), pendingIntent)
}
private fun createEventPushPendingIntent(event: EntityObject): PendingIntent {
val intent = Intent(ctx, EventScheduleBroadcastReceiver::class.java)
.putExtra(EXTRA_EVENT_INFO, EventInfo(event))
return PendingIntent.getBroadcast(ctx, event.id, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
在这种情况下,我使用PendingIntent.FLAG_UPDATE_CURRENT
但实际上我尝试了所有标志和0。
这是我捕捉消息的方式:
class EventScheduleBroadcastReceiver : BroadcastReceiver() {
private val lifeCycleManager = DCLifecycleManager.getInstance()
override fun onReceive(context: Context, intent: Intent) {
val serializableEventInfo: Serializable? = intent.getSerializableExtra(EventInfo.EXTRA_EVENT_INFO)
if (serializableEventInfo is EventInfo) {
lifeCycleManager.pushProcessor.pushEventSchedule(context, serializableEventInfo)
}
}
}
我的广播接收者在清单中:
<receiver android:name="ru.campuz.feature.schedule.EventScheduleBroadcastReceiver" />
我的问题是:在方法onReceive
的Android 7.0上,我总是在intent
中获得空的额外内容。但是在下面的所有其他版本中,我得到intent
附加内容。我总是希望得到intent
附加内容。
我该怎么做才能修复它?
答案 0 :(得分:0)
Context.registerReceiver()仍然有效。 所以我已经在扩展Application类的类中注册了LocalBroadcastReceiver
private fun registerNetReceiver() {
val bManager = LocalBroadcastManager.getInstance(this)
val intentFilter = IntentFilter()
intentFilter.addAction(G.NET_DISCONNECT)
bManager.registerReceiver(mMessageReceiver, intentFilter)
}
//call when in factor page we go back and want to apply food count change in foods item in Product adapter
private val mMessageReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == G.NET_DISCONNECT){
val actType = intent.getIntExtra("ACT_TYPE",0)
val i = Intent(MyApplication.instance(),NetDisActivity::class.java)
i.putExtra("ACT_TYPE",actType)
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(i)
}
}
}
并在整个活动中使用此方法检查网络连接
fun isNetworkAvailable(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetworkInfo = connectivityManager.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnected
}
如果top方法返回false,则像下面这样调用广播
val intent = Intent(G.NET_DISCONNECT)
intent.putExtra("ACT_TYPE",actType) //even can pass data
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)