I’ve experienced this issue before and I noticed a lot of people are also having the same issue and perhaps you have ask the question over again that why does my phone only charge when off? Strange I guess; the truth is, to every android phone problem, there is always a solution.
There are few reasons why your smartphone refuse to charge while turned on but charges while turned off which includes; outdated software’s, bent pin (pin sometimes get bent to a different position that makes charging a hassle, and changes how the phone is recognized if at all. Because of that, you can only charge the phone when it’s off.)
Power off your phone, and wait for like fifteen seconds before you start getting setup to fix the issue
Examine the port carefully to see where the pin is bent
Straighten out the pin carefully to avoid causing any damage to it.
Once the pin is fixed properly, try to charge it when turn on and see the difference.
Use different USB cable and charger to power up your device when turn on. Sometimes, cable tend to be incompatible with some phones with time.
Remove/Refresh your battery: if your smartphone have a removable battery, I suggest you remove it completely and use another different battery compatible with your smart phone. Battery incompatibility sometimes causes charging distortion.
Make sure Your Android softwareis up to date otherwise search for an update for your device and get it updated. System crashes when they are out dated.
Factory reset your Phone: When all the above fails, then you will have to do the needful by factory resetting your phone.
Hope this help? If you are any issue relating to those, kindly point it out using the comment box.