将解析信息添加到 Robolectric 包管理器 [英] Add resolve info to Robolectric package manager

查看:37
本文介绍了将解析信息添加到 Robolectric 包管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个 SO 问题与我想要做的非常相似:如何使用 Robolectric 隐藏 PackageManager

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

然而,所有的答案都依赖于 ShadowApplication.setPackageManager().在 2.2 中,此方法似乎不再存在:http://robolectric.org/javadoc/org/robolectric/shadows/ShadowApplication.html

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?

推荐答案

Intent.resolveActivity 期望 ResolveInfo 具有以下内容:

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

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

因此,基于此,以下在 Robolectric 2.3 中对我有用:

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);

这篇关于将解析信息添加到 Robolectric 包管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆