I've got Sony Z1 Compact with non-rooted Android 5.1.1.
It has an issue with some of my wired headsets: any slight movement of the phone with headset connected causes the phone to stop playback despite the fact that headset remains connected. (the playback can be started again with use of headset button)
I think the reason is a slightly loose jack port on my device because my other devices don't have this problem with the same headsets.
So it seems that the only software solution (without manual toggling headset-mode) would be to create some reasonable delay at which device decides that the headset was indeed disconnected and I'm looking for the way to achieve this behavior.