本文介绍了在 Espresso android 中获取当前活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果测试跨越多个活动,有没有办法获取当前活动?
In case of a test that crosses multiple activities, is there a way to get current activity?
getActivtiy() 方法只给出一个用于启动测试的活动.
getActivtiy() method just gives one activity that was used to start the test.
我尝试过类似下面的方法,
I tried something like below,
public Activity getCurrentActivity() {
Activity activity = null;
ActivityManager am = (ActivityManager) this.getActivity().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
try {
Class<?> myClass = taskInfo.get(0).topActivity.getClass();
activity = (Activity) myClass.newInstance();
}
catch (Exception e) {
}
return activity;
}
但我得到空对象.
推荐答案
在 Espresso 中,您可以使用 ActivityLifecycleMonitorRegistry
但它没有得到官方支持,因此在未来版本中可能无法使用.
In Espresso, you can use ActivityLifecycleMonitorRegistry
but it is not officially supported, so it may not work in future versions.
这是它的工作原理:
Activity getCurrentActivity() throws Throwable {
getInstrumentation().waitForIdleSync();
final Activity[] activity = new Activity[1];
runTestOnUiThread(new Runnable() {
@Override
public void run() {
java.util.Collection<Activity> activities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED);
activity[0] = Iterables.getOnlyElement(activities);
}});
return activity[0];
}
这篇关于在 Espresso android 中获取当前活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!