我有问题。在不同手机上运行我的测试时,在尝试打开图库时,它无效。
现在,我想要做的是获取默认的gallery opener app的包名,所以我可以在我的代码中使用它。我该如何以编程方式执行此操作?
以下是我在Nexus 5上运行测试时的使用方法。
Resources resources = InstrumentationRegistry.getTargetContext().getResources();
Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
resources.getResourcePackageName(R.drawable.ic_launcher) + '/' +
resources.getResourceTypeName(R.drawable.ic_launcher) + '/' +
resources.getResourceEntryName(R.drawable.ic_launcher));
Intent resultData = new Intent();
resultData.setData(imageUri);
Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);
intending(toPackage("com.google.android.apps.photos")).respondWith(result);
//Click the select button
onView(withId(R.id.register_image)).perform(click());
threadSleep(MILISECONDS_TIMEOUT);
onView(withText("From Gallery")).perform(click());
threadSleep(MILISECONDS_TIMEOUT);
Spoon.screenshot(getActivityInstance(), "picture_selected");
基本上,我需要做的就是获取图像应用程序的包名。
答案 0 :(得分:2)
所以,你会想做这样的事情:
创建utils类并添加以下方法:
public static String getPackageForGalery() {
Intent mainIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
mainIntent.setType("image/*");
List<ResolveInfo> pkgAppsList = getApplicationContext().getPackageManager().queryIntentActivities(mainIntent, PackageManager.GET_RESOLVED_FILTER);
int size = pkgAppsList.size();
for (ResolveInfo infos : pkgAppsList) {
return infos.activityInfo.processName;
}
return null;
}
现在,在您的代码中,执行以下操作:
Resources resources = InstrumentationRegistry.getTargetContext().getResources();
Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
resources.getResourcePackageName(R.drawable.ic_launcher) + '/' +
resources.getResourceTypeName(R.drawable.ic_launcher) + '/' +
resources.getResourceEntryName(R.drawable.ic_launcher));
Intent resultData = new Intent();
resultData.setData(imageUri);
Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);
intending(toPackage(YourUtilsClass.getPackageForGalery())).respondWith(result);
//Click the select button
onView(withId(R.id.register_image)).perform(click());
threadSleep(MILISECONDS_TIMEOUT);
onView(withText("From Gallery")).perform(click());
threadSleep(MILISECONDS_TIMEOUT);
Spoon.screenshot(getActivityInstance(), "picture_selected");
答案 1 :(得分:1)
PackageManager是你的朋友。特别是要获取所有应用程序的列表,您可以使用该类型的意图 queryIntentActivities(Intent intent, int flags)。这将返回一个匹配活动的列表,这些活动是针对最受欢迎的订购意如果与解析器不匹配,则列表将为空,这可能意味着您的意图未正确形成。