How to detect when app is minimized or the phone is locked?

I have a bluetooth connection to an arduino. I want to close it when the app is minimized or the phone is locked to allow other phones to connect to the arduino. (I'ts just a remote controller for a fancy lamp, so I could disconnect when the user hasn't changed anything for 60 seconds but I prefer the first way.)

Here is an extension only for this purpose:

This sounds more like a job for the Arduino, since it is supposedly running continually, as opposed to the phone, which might wander away out of range or lose power.

The Arduino could keep a variable with the timestamp (ms) of the last command, and check it in a loop for when it is older than your preferred limit.
If it's been too long since the last command, break the connection.

Yeah but in my experience when the app is running in the background, it randomly sends the data every few seconds (~1-10sec) So the arduino wouldn't time out.

In that case, Anke's solution would be better to detect campers.

lol I love how you used the word 'campers'. But it's actually not that serious. I just don't want random coumminications to happen. "I'm camping the lamp, no one can control it!"