Why BroadcastReceiver works even when app is in background ?

后端 未结 9 925
感动是毒
感动是毒 2020-12-04 13:59

I am checking Internet connectivity in my app using BroadcastReceiver and I show an alert dialog if the connection is lost. It works fine. But my problem is that BroadcastRe

9条回答
  •  旧时难觅i
    2020-12-04 14:08

    A BroadcastReceiver works when the app is in the background because the event that the receiver picks up are sent globally, and each app is registered to listen in on these, regardless of whether or not it is running.

    To deal with this, in your BroadcastReceiver's onReceive code, check if your app is in the foreground.

    There is one--and only one that I know of--consistently effective method to do this. You need to keep track of your pause/resume actions for your application. Ensure that you check this in every activity.

    There is some sample code in this answer (solution #1). In your case, you would want to check MyApplication.isActivityVisible() == true as a validation before doing anything from your BroadcastReceiver.

提交回复
热议问题