Android UIAutomator获取应用启动Intent为空问题求助
getLaunchIntentForPackage返回null无法启动应用 我正在开发一款Android应用,尝试使用UIAutomator编写UI测试。在测试初始化的@Before方法中,希望从启动器重新启动应用,参考官方教程编写了代码,但调用getLaunchIntentForPackage(<包名>)方法始终返回null,无法定位原因。请问需要修改代码或AndroidManifest.xml(或其他地方)的哪些内容,才能让该方法定位并返回应用的启动Intent,从而启动应用?
测试代码
... // 省略导入语句 ... @RunWith(AndroidJUnit4.class) @SdkSuppress(minSdkVersion = 18) public class DisplayFilesTest { private static final String PACKAGE_NAME = DisplayFiles.class.getPackageName(); private static final int LAUNCH_TIMEOUT = 5000; private UiDevice device; @Before public void startMainActivityFromHomeScreen() { // 初始化UiDevice实例 device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); // 回到主屏幕 device.pressHome(); // 等待启动器加载完成 final String launcherPackage = device.getLauncherPackageName(); assertThat(launcherPackage, notNullValue()); device.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT); final Context context = ApplicationProvider.getApplicationContext(); assertThat(context, notNullValue()); final Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(PACKAGE_NAME); assertThat(launchIntent, notNullValue()); // <<<<=== 此处断言始终触发,因为返回的Intent为null // 清除之前的应用实例 launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); // 启动应用 context.startActivity(launchIntent); // 等待应用启动完成 device.wait(Until.hasObject(By.pkg(PACKAGE_NAME).depth(0)), LAUNCH_TIMEOUT); } // 后续添加实际UI测试用例... }
AndroidManifest.xml中入口Activity配置
... <activity android:name=".activities.DisplayFiles" android:icon="@drawable/icon" android:exported="true" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ...
解决方案
验证包名准确性:当前代码通过
DisplayFiles.class.getPackageName()获取包名,若测试类与目标Activity不在同一包下,或混淆导致包名不一致,会获取错误值。建议直接硬编码应用的正式包名(如com.example.myapp)测试,确认是否为包名问题。确认入口Activity的Intent-Filter配置:
- 确保没有其他Activity配置了相同的
MAINaction +LAUNCHERcategory,否则系统无法确定默认启动入口; - 检查是否存在
tools:node="remove"等属性意外移除了Intent-Filter配置。
- 确保没有其他Activity配置了相同的
更换Context获取方式:将
ApplicationProvider.getApplicationContext()替换为InstrumentationRegistry.getInstrumentation().getTargetContext(),后者更准确指向被测应用的上下文,能正确获取其PackageManager信息。手动构造启动Intent(备选方案):若上述方法无效,可跳过
getLaunchIntentForPackage,直接指定组件构造Intent:Intent launchIntent = new Intent(Intent.ACTION_MAIN); launchIntent.addCategory(Intent.CATEGORY_LAUNCHER); launchIntent.setPackage(PACKAGE_NAME); // 替换为你的Activity全类名 launchIntent.setComponent(new ComponentName(PACKAGE_NAME, "com.example.activities.DisplayFiles")); launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);确认应用安装状态:通过
adb shell pm list packages | grep 你的包名检查被测应用是否已正确安装在测试设备上,且与测试用例签名一致(尤其是Debug版本)。
内容的提问来源于stack exchange,提问作者mmo

