On Samsung mobile phones, how does its USB host know when to charge the phone and when to power the connected device?
It is done with the USB OTG. Usb mini and micro have a OTG pin that the phone uses to know if it's supposed to be host or slave.

Usb C has a more complicated signaling system but the idea is the same.