0

I have registered a Broadcast receiver in my application's manifest file like:

<receiver android:name="com.example.devicecommunication.MainActivity$proximityOffReceiver" android:enabled="true"> 
        <intent-filter> 
            <action android:name="com.example.devicecommunication.PROXIMITYOFF" /> 
        </intent-filter> 
</receiver> 

I have defined the receiver in MainActivity (as I want the receiver to be executed even when the activity is not in the foreground). I saw the link Android - how to unregister a receiver created in the manifest?. But I am confused if I should explicitly unregister the receiver, each time when the application is quit or when the back button is pressed? Thanks in advance!

Community
  • 1
  • 1
user1741274
  • 759
  • 3
  • 13
  • 25

3 Answers3

2

I have defined the receiver in MainActivity (as I want the receiver to be executed even when the activity is not in the foreground).

Since proximityOffReceiver is a static inner class, the fact that you have it inside MainActivity does not mean that "when the activity is not in the foreground" affects proximityOffReceiver.

But I am confused if I should explicitly unregister the receiver, each time when the application is quit or when the back button is pressed?

The accepted answer on that question points out that you do not "unregister" a receiver that is registered in the manifest. You enable or disable the receiver.

Hence, in your case, you enable the receiver when you want it operating, and you disable the receiver when you do not want it operating. In your case, it would appear that you want it operating all of the time, in which case you probably never disable it.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
1

Whether to Register or UnRegister a Receiver depends on your usage. There is no need of explicitly unregister the reciever, each time when the application is quit/when back button is preseed.

Avadhani Y
  • 7,566
  • 19
  • 63
  • 90
1

You should only put a receiver in the manifest if you want it to happen whether your activity is running or not. If you want to turn it on only after your app is launched, then it should be registered in code by your activity. Unless you have a receiver that you want to be on almost all the time and turn it off only for brief periods, then there's no reason to unregister it once set in the manifest.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127