Set preferred device in order to trigger routed device changed event.

For MediaPlayer case, the routing callback listener may be added after
the output device is selected. In that case, current test may fail. Set
a device that is different from routed device may cause the routed
device changed.

Test: run RoutingTest
Bug: 129696133
Change-Id: I665fb60ed6d91868702af4b36e045509c6533736
diff --git a/tests/tests/media/src/android/media/cts/RoutingTest.java b/tests/tests/media/src/android/media/cts/RoutingTest.java
index e1765d8..f2e078a 100644
--- a/tests/tests/media/src/android/media/cts/RoutingTest.java
+++ b/tests/tests/media/src/android/media/cts/RoutingTest.java
@@ -666,6 +666,12 @@
             return;
         }
 
+        AudioDeviceInfo[] devices = mAudioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
+        if (devices.length < 2) {
+            // In this case, we cannot switch output device, that may cause the test fail.
+            return;
+        }
+
         mRoutingChanged = false;
         mRoutingChangedLooper = null;
         // Create MediaPlayer in another thread to make sure there is a looper active for events.
@@ -678,6 +684,27 @@
                 AudioRoutingListener listener = new AudioRoutingListener();
                 MediaPlayer mediaPlayer = allocMediaPlayer();
                 mediaPlayer.addOnRoutingChangedListener(listener, null);
+                // With setting preferred device, the output device may switch.
+                // Post the request delayed to ensure the message queue is running
+                // so that the routing changed event can be handled correctly.
+                Handler handler = new Handler();
+                handler.postDelayed(new Runnable() {
+                    @Override
+                    public void run() {
+                        AudioDeviceInfo routedDevice = mediaPlayer.getRoutedDevice();
+                        if (routedDevice == null) {
+                            return;
+                        }
+                        AudioDeviceInfo[] devices = mAudioManager.getDevices(
+                                AudioManager.GET_DEVICES_OUTPUTS);
+                        for (AudioDeviceInfo device : devices) {
+                            if (routedDevice.getId() != device.getId()) {
+                                mediaPlayer.setPreferredDevice(device);
+                                break;
+                            }
+                        }
+                    }
+                }, 1000);
                 Looper.loop();
                 mediaPlayer.removeOnRoutingChangedListener(listener);
                 mediaPlayer.stop();