Android BroadcastReceiver onReceive() called twice on android 4.0

前端 未结 15 2332
梦谈多话
梦谈多话 2020-12-29 20:38

I faced to one problem on android 4.0.3 (on 4.1.2 it works fine). I have in my Activity BroadcastReceiver. When I send a broadcast, method onReceive() called always twice. P

15条回答
  •  滥情空心
    2020-12-29 20:47

    I had same issue.

    onReceive() gets called twice because i was registering Broadcast receiver twice. One in my activity's onCreate() and another in manifest.

    I remove broadcast receiver registration from onCreate() and it's working fine. Register your broadcast receiver in only one of them.

    There are two ways to do this:

    • Statically in the manifest file.
    • Dynamically in the code.

    Which method (static or dynamic) to use when depends completely upon what you’re trying to do. Basically when you want to do some changes right on the screen (home screen, launcher, status bar, etc.) by showing up some notification or some indicator in the status bar by listening to system wide events or maybe those sent by other apps, then it make sense to use statically registered broadcast receivers. Whereas based on similar events you want to do changes right in your app when the user is using it or maybe it’s put in the background, then it makes sense to use dynamically registered receivers which’ll last till the registering components are destroyed.

    For more info: http://codetheory.in/android-broadcast-receivers/

提交回复
热议问题