如何使用 Robotium/Android SDK 找出哪个 Activity 在栈顶?

How to find out which Activity is on top of the stack using Robotium/Android SDK?

我有一个 Android 应用程序的 Robotium 测试,它扩展了 ActivityInstrumentationTestCase2。测试循环运行,随机点击活动视图。我想在每次迭代开始时验证 Activity 当前关注的是哪个。这种行为对我来说很重要,因为其中一个按钮能够启动另一个 Activity,因此无法在循环中进行进一步的操作,因为它们指的是正在测试的 Activity(这是我停止机器人测试)。

我想要一个适用于任何 Activity 的通用解决方案,而无需更改 onDestroy() 方法。当按下主页按钮时,此解决方案也必须适用。

您应该可以使用

solo.getCurrentActivity()

为此目的,这对您不起作用吗?如果没有,我会提前解决潜在问题,并在您构建单独对象时询问您的代码以及您使用的是哪个版本的 roborium。

这个适合我,最低 SDK 级别是 18

public static Activity getCurrentActivity(){
    try {
        Class activityThreadClass = Class.forName("android.app.ActivityThread");
        Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
        Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
        activitiesField.setAccessible(true);
        ArrayMap activities = (ArrayMap) activitiesField.get(activityThread);
        for (Object activityRecord : activities.values()) {
            Class activityRecordClass = activityRecord.getClass();
            Field pausedField = activityRecordClass.getDeclaredField("paused");
            pausedField.setAccessible(true);
            if (!pausedField.getBoolean(activityRecord)) {
                Field activityField = activityRecordClass.getDeclaredField("activity");
                activityField.setAccessible(true);
                Activity activity = (Activity) activityField.get(activityRecord);
                return activity;
            }
        }
    }catch (Exception e){
        logger.error(e.getMessage());
    }
    return null;
}

我们发现,this link 包含了这个问题的答案。

ActivityManager am = (ActivityManager) this .getSystemService(ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
Log.d(WebServiceHelper.TAG, "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName()+"   Package Name :  "+componentInfo.getPackageName());