You can earn Mega Energy by defeating a Mega-Evolved Pokémon in a Mega Raid Battle or by completing specific research tasks. You can also occasionally earn Mega Energy by walking with your Buddy Pokémon if you have previously Mega-Evolved a Pokémon in your Buddy Pokémon's Evolutionary line.