to prevent similar things to occur to me, i have developed two weapons i use regularly:
1. i put my headphones on and turn on the music on my mobile pretty loudly - even if someones trying to talk to and I do not see it, I do not know - very rarely someone tries to get my attention by waving a hand or touching me - it usually is important then like helping that person or just letting one to pass (eg. in a subway) - but with most of the cases, it works since I cannot really tell im bothered in public
2. when I eventually am - and it's a case i am expected to give an answer, i use a geeky one - using some not very common words or speaking very literacy language usually makes people like "ok, thanks bud"... if it doesn't scare the person out, who knows, maybe it's worth talking to him/her?