It's actually a lot simpler to do this than you might think. You only really need to hear two or three chords to be able to determine the key of a song. The knowledge you need is the major scale and how to harmonise it to build chords. With that, you can figure out the key of any song that uses the major scale (that's like 90% of western music).
For example, if you hear Bm followed by C#m, you know the song is in A, as only that key has the Bm followed by a C#m. If you hear Gm followed by Adim, you know the song is in the key of A#. If you hear D#m followed by E, you know the song is in B.
In other cases, you may need a third chord. If you hear G#m followed by E, the song could be in the key of E or B. You'll need either a third chord to distinguish between them.
Conversely, if the chords are made of four notes (they include the 7th), you may only need one chord to determine the key. If you hear an E7 chord, you know the song is in A. If you hear an Fdim, you know the song is in the key of F#.
Learn the major scale and how to build chords for each step of it. From that, learn the order of the chords it produces (that order is major 7th, minor 7th a whole step up, minor 7th a whole step up, major 7th a half step up, dominant 7th a whole step up, minor 7th a whole step up, diminished a whole step up, and a final half step up to the starting chord again).
With that info, it's a very simple process of elimination to figure out the key of any piece. Then you can choose to play the appropriate scale over it for your melody or build chord voicings.
I'm writing a guide to music theory that's aimed at total beginners, and I've covered this way more extensively in it, but that should be enough to get you going. If you like, I'll happily share what I've written so far (5 chapters/sections, covering an introduction the major scale, its modes and harmony, and some stuff on extended harmony). Just drop me a PM.