Added condition to prevent application from freezing when device is disconnected.