我正在运行一些UI测试(espresso + ui automator)。我想测试系统在后台重新启动的应用程序。我读过的大多数东西都建议使用android.os.Process.killProcess(processid);
我在测试类中运行了此方法:
public void forceQuit() {
Context context = InstrumentationRegistry.getTargetContext();
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> pids = am.getRunningAppProcesses();
int processid = 0;
for (int i = 0; i < pids.size(); i++) {
ActivityManager.RunningAppProcessInfo info = pids.get(i);
if (info.processName.equals("com.example.debug")) {
Log.d("TAG, ", "ABOUT TO FORCE QUIT: " + info.processName);
processid = info.pid;
}
}
if (processid != 0) {
android.os.Process.killProcess(processid);
}
}
问题在于应用程序和检测在同一进程中运行。还有其他方法可以做到而又不会使整个测试崩溃吗?
更新:
正如@CommonsWare指出的那样,这并不是Android真正处理的方式。我应该从日志中知道这一点:
2018-09-18 17:13:13.858 30357-30445/com.example.debug D/TAG,: ABOUT TO FORCE QUIT
2018-09-18 17:13:13.859 30357-30445/com.example.debug I/Process: Sending signal. PID: 30357 SIG: 9
...
2018-09-18 17:13:13.904 3238-5855/? I/WindowManager: WIN DEATH: Window{74da2c7 u0 com.example.debug/com.example.main.MainActivity}
...
2018-09-18 17:13:13.905 3238-30027/? I/ActivityManager: Process com.example.debug (pid 30357) has died: fore TOP
2018-09-18 17:13:13.907 3238-30027/? W/ActivityManager: Scheduling restart of crashed service com.example.debug/com.example.MyOtherService in 1000ms
2018-09-18 17:13:13.908 3238-30027/? W/ActivityManager: Scheduling restart of crashed service com.example.debug/com.example.MyService in 10998ms
2018-09-18 17:13:13.908 3238-30027/? W/ActivityManager: Force removing ActivityRecord{e29eba9 u0 com.example.debug/com.example.main.MainActivity t12323}: app died, no saved state
2018-09-18 17:13:13.909 3238-3292/? W/zygote64: kill(-30357, 9) failed: No such process
...
2018-09-18 17:13:13.916 3238-4737/? W/WindowManager: removeWindowToken: Attempted to remove non-existing token: android.os.Binder@a45bb61
...
2018-09-18 17:13:13.921 3238-30027/? W/ActivityManager: Crash of app com.example.debug running instrumentation ComponentInfo{com.example.debug.test/com.example.e2etests.E2ETestRunner}
2018-09-18 17:13:13.921 3238-30027/? I/ActivityManager: Force stopping com.example.debug appid=10686 user=0: finished inst
2018-09-18 17:13:13.922 3238-30630/? W/Binder: Outgoing transactions from this process must be FLAG_ONEWAY
java.lang.Throwable
at android.os.BinderProxy.transact(Binder.java:752)
at android.app.IInstrumentationWatcher$Stub$Proxy.instrumentationFinished(IInstrumentationWatcher.java:160)
at com.android.server.am.InstrumentationReporter$MyThread.run(InstrumentationReporter.java:86)
2018-09-18 17:13:13.924 3238-30027/? I/ActivityManager: Force stopping service ServiceRecord{1efa5d5 u0 com.example.debug/com.example.MyOtherService}
2018-09-18 17:13:13.924 3238-30027/? I/ActivityManager: Force stopping service ServiceRecord{16f8bbd u0 com.example.debug/com.example.MyService}