Call Dialog#dismiss() in runOnMainSync().

Dialog must be dismissed before the activity is destroyed. After
Activity#onDestory(), calls to Dialog#dismiss() would generate
IllegalArgumentException.

Calling Dialog#dismiss() on the test thread may be dangerous, because
1. dismiss() will post a task onto UI thread. At the point when the
   task is executed, the activity may have already been destroyed.
2. when the activity is destroyed unexpectedly before dismiss(), the
   test process will terminate because IllegalArgumentException will be
   thrown on UI thread from the posted task. This will cause
   successive test cases to fail together.

MonitoringInstrumentation#runOnMainSync() catches the exception if an
exception is thrown on UI thread, and rethrows it on the caller thread.
https://developer.android.com/reference/androidx/test/runner/MonitoringInstrumentation#runOnMainSync(java.lang.Runnable)
We can use it to avoid crashing the test process.

As runOnMainSync() is called in a try-with-resources statement, the
original exception (if any) is kept and IllegalArgumentException will be
added as a suppressed exception.

Bug: 202091561
Bug: 201698483
Test: atest CtsInputMethodTestCases
Test: Enabled "Don't keep activities" option, and verified that
      CtsInputMethodTestCases completes without crash.
Merged-In: I86cb92fb732aaddd76bdf0df07d54ea404b384fc
Change-Id: I86cb92fb732aaddd76bdf0df07d54ea404b384fc
(cherry picked from commit f20716713132c3d85a016cfe5baea254a95f3193)
1 file changed