[英]How to clear the activity stack and bring a running activity to foreground in Android?
[英]How to assert the activity running in foreground?
我有一个DeepLinkHandlerActivity
类,可以处理我的所有深层链接。 为了对其进行测试,我编写了以下代码。 无法弄清楚如何测试一段时间后前台的活动是否是期望的活动? 知道怎么做吗?
class DeepLinkHandlerTest {
@Before
@Throws(Exception::class)
fun setUp() {
}
@After
@Throws(Exception::class)
fun tearDown() {
}
@get:Rule
val activityTestRule = ActivityTestRule<DeepLinkHandlerActivity>(DeepLinkHandlerActivity::class.java)
@Test
fun validalidUrlTest() {
val url = "myapp://loadwebview"
triggerDeeplink(url)
Thread.sleep(5000)
// what to do here?
// some form of assertion that correct activity is in foreground.
}
private fun triggerDeeplink(url: String) {
val intent = Intent("android.intent.action.VIEW", Uri.parse(url))
activityTestRule.launchActivity(intent)
}
}
一种方法是在每个活动中都有一个静态标志,并在该活动的onPause和onResume方法上触发它。 那么您可以检查该标志以查看活动是否在前台。
有一种来自android蓝图的方法,但我不确定它是否有效。
/**
* Gets an Activity in the RESUMED stage.
* <p>
* This method should never be called from the Main thread. In certain situations there might
* be more than one Activities in RESUMED stage, but only one is returned.
* See {@link ActivityLifecycleMonitor}.
*/
public static Activity getCurrentActivity() throws IllegalStateException {
// The array is just to wrap the Activity and be able to access it from the Runnable.
final Activity[] resumedActivity = new Activity[1];
getInstrumentation().runOnMainSync(new Runnable() {
public void run() {
Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance()
.getActivitiesInStage(RESUMED);
if (resumedActivities.iterator().hasNext()) {
resumedActivity[0] = (Activity) resumedActivities.iterator().next();
} else {
throw new IllegalStateException("No Activity in stage RESUMED");
}
}
});
return resumedActivity[0];
}
最终做了这样的事情:
https://www.codexpedia.com/android/ui-test-deep-linking-using-espresso-in-android/
如果有更好的方法,欢迎提出建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.