为什么 Instrumentation Registry (UI-automator) 中的 PackageManager 找不到 Activity?
意图 { pkg=com.me.Activity1 }
我的应用程序有 3 个入口点。三个活动,每个活动都由一个图标表示。
我正在尝试运行 ui-automator 测试来按下图标并启动相应的活动。
在 Android Studio 2.2 中,当我选择应用程序并按“运行”时,它会正确运行并启动活动。但是,在 ui-automator 中,它在 Nexus 5 设备和模拟器中均失败。
但是,按照文档中提供的示例,“访问 UI 组件 https://developer.android.com/training/testing/ui-testing/uiautomator-testing.html#run”,意图是无效的。
我找到了这个answer https://stackoverflow.com/q/30446052/398348并尝试修改。由于意图是显式创建的,因此它不再为 null,但它不会启动 Activity - logcat 显示它没有启动。
调试显示resolveInfos.size为零。我猜测上下文或仪器注册表有问题。
Collections.sort(resolveInfos, new ResolveInfo.DisplayNameComparator(pm));
我也尝试过... getTargetContext() 而不是 getContext(),但失败了。
Context context = InstrumentationRegistry.getTargetContext();
任何帮助表示赞赏。
@Test
public void userLaunchesActivity1() {
launchApp("com.me.Activity1");
}
void launchApp(String BASIC_SAMPLE_PACKAGE) {
Log.d("userLaunchesActivity1", "BASIC_SAMPLE_PACKAGE:"+BASIC_SAMPLE_PACKAGE);
// Initialize UiDevice instance
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
// Start from the home screen
mDevice.pressHome();
// Wait for launcher
final String launcherPackage = mDevice.getLauncherPackageName();
assertThat(launcherPackage, notNullValue());
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
LAUNCH_TIMEOUT);
// Launch the app
Context context = InstrumentationRegistry.getContext();
// ======== example from android.com documentation - intent is null ====
// Description
// final Intent intent = context.getPackageManager()
// .getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE);
// Clear out any previous instances
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//context.startActivity(intent);
//
//=======stack overflow answer - does not launch activity====================
Intent intent = new Intent();
intent.setPackage(BASIC_SAMPLE_PACKAGE);
PackageManager pm = context.getPackageManager();
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
Collections.sort(resolveInfos, new ResolveInfo.DisplayNameComparator(pm));
//======= this is not entered at all ===================
if(resolveInfos.size() > 0) {
ResolveInfo launchable = resolveInfos.get(0);
ActivityInfo activity = launchable.activityInfo;
ComponentName name = new ComponentName(activity.applicationInfo.packageName,
activity.name);
Intent i = new Intent(Intent.ACTION_MAIN);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.setComponent(name);
context.startActivity(i);
}
//===========================
// Wait for the app to appear
mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)),
LAUNCH_TIMEOUT);
}