tracks: Check track states before transitioning states

Prevents sporadic crashes when the user plugs/unplugs the headset
rapidly. These were caused by performing track operations such as start,
stop and record before checking whether the tracks had been stopped
before.

Change-Id: I54b5ba102ffbed4c453ee5f15533467e5f4771fd
Ticket: CYNGNOS-2775
diff --git a/src/com/android/fmradio/FmService.java b/src/com/android/fmradio/FmService.java
index b3d7715..973dceb 100644
--- a/src/com/android/fmradio/FmService.java
+++ b/src/com/android/fmradio/FmService.java
@@ -396,7 +396,7 @@
            mAudioRecord.release();
            mAudioRecord = null;
        }
-       if (mAudioTrack != null) {
+       if (mAudioTrack != null && mAudioTrack.getState() == AudioTrack.STATE_INITIALIZED) {
            mAudioTrack.stop();
            mAudioTrack.release();
            mAudioTrack = null;
@@ -448,7 +448,8 @@
     }
 
     private void startAudioTrack() {
-        if (mAudioTrack.getPlayState() == AudioTrack.PLAYSTATE_STOPPED) {
+        if (mAudioTrack.getState() == AudioTrack.STATE_INITIALIZED
+                && mAudioTrack.getPlayState() == AudioTrack.PLAYSTATE_STOPPED) {
             ArrayList<AudioPatch> patches = new ArrayList<AudioPatch>();
             mAudioManager.listAudioPatches(patches);
             mAudioTrack.play();
@@ -477,11 +478,13 @@
                         // Speaker mode or BT a2dp mode will come here and keep reading and writing.
                         // If we want FM sound output from speaker or BT a2dp, we must record data
                         // to AudioRecrd and write data to AudioTrack.
-                        if (mAudioRecord.getRecordingState() == AudioRecord.RECORDSTATE_STOPPED) {
+                        if (mAudioRecord.getRecordingState() == AudioRecord.RECORDSTATE_STOPPED
+                                && mAudioRecord.getState() == AudioRecord.STATE_INITIALIZED) {
                             mAudioRecord.startRecording();
                         }
 
-                        if (mAudioTrack.getPlayState() == AudioTrack.PLAYSTATE_STOPPED) {
+                        if (mAudioTrack.getPlayState() == AudioTrack.PLAYSTATE_STOPPED
+                                && mAudioTrack.getState() == AudioTrack.STATE_INITIALIZED) {
                             mAudioTrack.play();
                         }
                         int size = mAudioRecord.read(buffer, 0, RECORD_BUF_SIZE);