First, remember that electrons cannot exist between principle energy levels (distances). In a flame, electrons from lower principle levels (n=1,2,3... etc) will be knocked up to higher principle levels from the absorbed energy. Electrons do not like to stay in this high energy state and will travel back down to their ground state, and in the process release that stored energy in the form of radiation (often visible light). The frequency of the radiation (color of the light) depends upon how big the fall back to ground state was. Different metals have different attainable energy levels, and so will display different colors when burned.
Some elements only have a few possible emission colors, while other elements are a mixture of dozens of colors ! This principle helps us tell what the composition of stars are, as well as allows us to test for metal contents in food products or other applications.