In this case, we consider the intrinsic aspect of flies. How annoying and inexhaustible they are are always there, behind your ear! And when you try to crush them, they escape and then, zigzagging back, they leave a buzz in our ears that sounds like a mocking laugh.
When someone says that “tiene la mosca detrás de la oreja” it means that they are afraid about something, they are angry for some reason which keep them unquiet. It is also used when you cannot stop thinking about something, as if you had a buzz in your ears that can’t leave you alone.
If you have a feeling that someone is plotting against you, that something unexpected will happen …so “tienes la mosca detrás de la oreja”.