Android N 7.0中的BroadcastReceiver

时间:2018-04-05 08:13:05

标签: android broadcastreceiver android-broadcastreceiver android-7.0-nougat

我想发送广播消息并在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附加内容。

我该怎么做才能修复它?

1 个答案:

答案 0 :(得分:0)

基于android document

,我在整个应用程序中都存在检查互联网连接的相同问题

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)