Example 1. I have a handheld vacuum cleaner and while I’m using it sometimes it goes dead and needs to be recharged. But if I turn it off and on again I get another minute out of it.
Example 2. If a flashlight gets dim, sometimes turning it off and then on again makes it brighter for a little while.
Batteries generate electricity though a chemical reaction. When you open the circuit, and leave the device off for awhile, it allows a little bit of the un-reacted chemicals in the battery to migrate to where they are needed. Turning the circuit back on will use up those chemicals pretty quickly, though.
As for the shaking, I would assume it would ‘reseat’ the connection between the battery and the device, potentially reducing the amount of oxidation between the two, lowering the resistance of he circuit and allowing greater voltage for the device. This also applies to the switch on the flashlight which can be partly cleaned by flipping it on and off a few times.
This must be why the trick works where, if a remote device stops working, you can open the little battery door, roll the batteries back and forth with your thumb a few times (while they are still in the remote), and often get a few more uses out of them.
Batteries are weird, and I’m not sure if anyone fully understands them. Battery voltage, for example, will steadily decrease as it’s being discharged. But when the load is removed, the battery voltage will steadily increase and then level off. And I think I read somewhere that subjecting a battery to a very brief short can sometimes allow you to get more energy from a battery, depending on its chemistry.