It's based on Handoff. Your devices already have a notion of which device you're currently using, which it uses to trigger Handoff (so you can resume an activity on your new device that you were just doing on a previous device). AirPods hook into that and switch input to the "current" device (but I believe only if it plays audio; that way picking up your iPhone won't disconnect you from your computer if you're not doing something audio-related. Of course, I don't have AirPods myself, so I can't verify, but I believe that's how it works).