获取默认图像openner的软件包名称
问题描述:
我遇到问题。在不同的手机上运行我的测试时,试图打开图库时,它不起作用。获取默认图像openner的软件包名称
现在,我想要做的是获取默认画廊开罐器应用程序的包名称,所以我可以在我的代码中使用它。我怎样才能以编程方式做到这一点?
这是为什么我在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");
基本上使用时,所有我需要做的就是以获取影像的应用程序的包名。
答
所以,你会想要做这样的事情:
创建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");
答
PackageManager是你的朋友在这里。具体来说,要获取所有听取您的类型意图的应用程序的列表,您可以使用 queryIntentActivities(Intent intent, int flags)。这将返回您的意向匹配活动列表从最喜欢的顺序。如果没有匹配解析器,则列表将为空,这可能意味着您的意图不正确。