I know this has been answered and replied many many times over, but I wanted to throw my 2 cents in because my old iPhone5 has this problem. And I think the reason for my focusing issues may be the problem for most of you. I have a hair or something stuck between the camera and lens on the inside.
So my thought is the camera is trying to focus on the hair a lot of the time. I've decided to leave it as the display has been replaced and I don't trust these cheap replacement screens from cracking as I open the phone back up.
So the banging might be moving around whatever it is that got stuck in your phone and therefore allowing the camera to focus.