如何在后台便捷杀死Activity/进程以测试UI数据恢复功能?
Got it, when you're running UI state restoration tests, being able to quickly kill activities or processes in the background is key to reliably reproducing scenarios and verifying if your app can recover data correctly. Below are the most practical methods I rely on:
This is my go-to for both manual testing and scripting. You'll need ADB set up on your computer and your device connected via USB debugging.
杀死指定Activity
First, grab the full class name of your target Activity while it's active with this command:adb shell dumpsys window | grep mCurrentFocusLook for a line like
mCurrentFocus=Window{xxxx u0 com.your.package/com.your.package.YourActivity}— the segment after the last slash is your Activity class name.Then kill it directly:
adb shell am force-stop com.your.package/com.your.package.YourActivity杀死整个应用进程
If you want to wipe the entire app from memory, use this command (you can get your app's package name viaadb shell pm list packagesor from your build.gradle file):adb shell am force-stop com.your.packageFor a more aggressive kill (simulating a system-initiated process termination):
adb shell kill -9 $(adb shell pidof com.your.package)
Perfect for on-the-go testing without a computer attached.
- First, enable Developer Options: Go to Settings > About Phone and tap Build Number 7 times until you see the "You're now a developer!" prompt.
- Head back to Settings and open Developer Options.
- Use one of these two options:
- 不保留活动 (Don't keep activities): Toggle this on. Now, as soon as you leave an Activity (press home or switch apps), the system will immediately destroy it. Reopen your app to check if the UI state is restored.
- 后台进程限制 (Background process limit): Set this to No background processes. Any app not in the foreground will have its processes killed right away. Switch away from your app and return to test state restoration.
- Before killing the Activity/process, add specific test data: fill out a form field, scroll to a specific list position, or open a detail page. This makes it easy to confirm if the state is properly recovered.
- For edge cases, try killing the app while it's performing a background task (like saving data) to ensure your state handling is robust.
内容的提问来源于stack exchange,提问作者Jim

