Appium测试结束后onDestroy()未被调用问题求助
Hey there, I’ve dealt with exactly this kind of Android lifecycle quirk when writing Appium E2E tests, so let’s break down how to fix it:
1. Force Proper App Lifecycle Triggers in @AfterMethod
The standard driver.quit() or closeApp() might not always trigger the full lifecycle on emulators because of how Appium interacts with the Android system. Try combining backgrounding the app first to ensure onPause() fires, then terminating the session:
@AfterMethod public void tearDown() { // Simulate pressing Home to send app to background (triggers onPause) driver.runAppInBackground(Duration.ofSeconds(3)); // Terminate the Appium session and destroy the app process driver.quit(); }
This mimics real user behavior more closely, which should prompt the system to run your onPause() logic and flush SharedPreferences changes (even with apply()).
2. Audit Your Desired Capabilities
Double-check that you haven’t set any capabilities that prevent Appium from stopping the app properly:
- Ensure
dontStopAppOnResetis not set totrue(this keeps the app running between test sessions) - If you’re using
noReset=true, make sure it’s not interfering with process cleanup—try toggling it temporarily to rule out conflicts
3. Force-Kill the App Process (Last Resort)
If the above doesn’t work, you can directly use ADB to terminate the app process, which guarantees Android will trigger onDestroy() and finalize any pending SharedPreferences writes:
@AfterMethod public void tearDown() { String appPackage = "com.your.package.name"; // Replace with your app's package try { // Execute ADB command to force-stop the app Runtime.getRuntime().exec("adb shell am force-stop " + appPackage); } catch (IOException e) { e.printStackTrace(); } driver.quit(); }
Android guarantees that apply() writes are persisted before a process is killed, so this should resolve the missing SharedPreferences changes.
4. Verify Your SharedPreferences Logic
Just to rule out code issues:
- Confirm you’re writing to
SharedPreferencescorrectly inonPause()/onDestroy()(no typos in the preference name, or incorrect mode likeMODE_PRIVATE) - Since
apply()is asynchronous, Android will handle flushing it to disk before the process exits—so this shouldn’t be the root cause, but it’s worth double-checking for uncaught exceptions in your lifecycle methods
5. Test on a Real Device or Different Emulator
Sometimes emulators (like Pixel 2) have system optimizations that delay or skip lifecycle methods for background apps. Try running your tests on a physical Android device or a different emulator (e.g., Nexus 5) to see if the issue is emulator-specific.
内容的提问来源于stack exchange,提问作者nat

