Add resolve info to Robolectric package manager

穿精又带淫゛_ 提交于 2019-12-23 09:14:49

问题


This SO question is very similar to what I want to do: How can I shadow the PackageManager with Robolectric

However, all the answers rely on ShadowApplication.setPackageManager(). In 2.2, this method no longer seems to exist: http://robolectric.org/javadoc/org/robolectric/shadows/ShadowApplication.html

I attempted to just grab the package manager and add a resolve info:

    RobolectricPackageManager packageManager = (RobolectricPackageManager) Robolectric.application.getPackageManager();
    Intent intent = new Intent(Intent.ACTION_MAIN,null);
    intent.addCategory(Intent.CATEGORY_HOME);
    ResolveInfo ri = new ResolveInfo();
    ActivityInfo ai = new ActivityInfo();
    ai.packageName = "com.fun.test";
    ri.activityInfo = ai;
    ri.isDefault = true;
    packageManager.addResolveInfoForIntent(intent, ri);

But to no avail. Does anyone know how to do this?


回答1:


Intent.resolveActivity is expecting the ResolveInfo to have the following:

if (info != null) {
    return new ComponentName(
            info.activityInfo.applicationInfo.packageName,
            info.activityInfo.name);
}

So based on that, the following works for me in Robolectric 2.3:

RobolectricPackageManager packageManager = (RobolectricPackageManager) shadowOf(Robolectric.application).getPackageManager();
Intent intent = ... //create an Intent like the one you want to resolve

ResolveInfo info = new ResolveInfo();
info.isDefault = true;

ApplicationInfo applicationInfo = new ApplicationInfo();
applicationInfo.packageName = "com.example";
info.activityInfo = new ActivityInfo();
info.activityInfo.applicationInfo = applicationInfo;
info.activityInfo.name = "Example";

packageManager.addResolveInfoForIntent(intent, info);



回答2:


You should adding the resolve info as a List:

packageManager.addResolveInfoForIntent(intent, Collections.singletonsList(ri));


来源:https://stackoverflow.com/questions/21638455/add-resolve-info-to-robolectric-package-manager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!