Android wifi p2p peers visibility

Actually you have valid observations, and that's the way the API actually works:

  1. So the device B is not visible until it doesn't start searching for other devices too

That's the way the API appears to work. Basically in order to be visible to other devices, the WiFi interface needs to be powered up and active, and so far I have seen it happening, when the device is either doing active discovery, or having active connection.

  1. The problem is that I want to establish a connection only if the app is running on both devices

Basically, I suppose best you can do, is to advertise the service while the app is running, and discover the service when connecting. This is Not 100% accurate alone, thus, you could also implement connection & handshake from client to Group owner to fully check that both ends are ok and present. If the handshake fails, then do disconnect.

  1. So when I start the searching on device B it receives the connection request from A, but nothing until then.

This one I don't have direct answer, Basically could be that something is not right there. I do know that if the device B is not active it should not be visible, and if the device B is not in actual Discovered peers list of the API, then all connection attempts to it will fail, so could be some combination of issues what happens here really.

  1. it shows some devices that hasn't the wifi enabled at that moment or that are out of range.

Supposing that the API does appear to cache some results some times, though have to admit that I have not seen this issue, I usually get peer changed events when I turn off a nearby device, and then Service discovery has not been giving any results on any device that would not really be there, so do try the service discovery always after you get Peers Changed event.