gpt4 book ai didi

android - 如何使隐含的 Intent 明确?

转载 作者:行者123 更新时间:2023-11-30 01:30:21 38 4
gpt4 key购买 nike

我有两个应用程序,A 和 B,它们使用 android 库 C。B 有一个服务 A 想通过 C 使用,例如

<service android:name="my.package.in.a.service.ConnectorService"
android:exported="true">
<intent-filter>
<action android:name="my.package.in.a.action.START_A"/>
</intent-filter>
</service>

在我的库中有一个类试图将它绑定(bind)到服务,例如

    Intent intent = new Intent("my.package.in.a.service.ConnectorService");
/** establish a connection with the service. */
boolean result = context.bindService(intent, messenger,
Context.BIND_AUTO_CREATE);

显然,由于安全问题(隐式与显式 Intent ),您不能再这样做了。我尝试使用 A 中定义的操作来初始化 Intent 。我还尝试添加包名称并尝试设置类名称,例如

   Intent intent = new Intent()
intent.setPackage("my.package.in.a.service");
intent.setClassName("my.package.in.a.service",
"my.package.in.a.service.ConnectorService");

我还尝试使用包管理器查找服务,例如

   Intent intent = new Intent("my.package.in.a.service.ConnectorService");
List<ResolveInfo> resolveInfoList = context.getPackageManager()
.queryIntentServices(intent, Context.BIND_AUTO_CREATE);

if (resolveInfoList.isEmpty()) {
Log.e(TAG, "could not find any service");
}

if (resolveInfoList.size() > 1) {
Log.e(TAG, "multiple services found");
}

我有点疑惑我做错了什么?据我了解,即使它不是同一包/应用程序的一部分,您也可以通过简单地指定包/类名来明确隐式 Intent 。然而,这一切似乎都失败了,显然我做错了什么?

最佳答案

我不认为 setPackage() 做得“足够”以使其完全明确。为此,你 need setComponent() .

您使用 PackageManager 的第二种方法是在正确的轨道上,但除非您只是截断了代码 list ,否则您错过了调整 Intent 的步骤。

this sample app来自 this book ,我不仅检查了服务的单个实现,还检查了它的签名(以确保我要绑定(bind)的应用程序没有被黑客入侵)并调整 Intent:

Intent implicit=new Intent(IDownload.class.getName());
List<ResolveInfo> matches=getActivity().getPackageManager()
.queryIntentServices(implicit, 0);

if (matches.size() == 0) {
Toast.makeText(getActivity(), "Cannot find a matching service!",
Toast.LENGTH_LONG).show();
}
else if (matches.size() > 1) {
Toast.makeText(getActivity(), "Found multiple matching services!",
Toast.LENGTH_LONG).show();
}
else {
ServiceInfo svcInfo=matches.get(0).serviceInfo;

try {
String otherHash=SignatureUtils.getSignatureHash(getActivity(),
svcInfo.applicationInfo.packageName);
String expected=getActivity().getString(R.string.expected_sig_hash);

if (expected.equals(otherHash)) {
Intent explicit=new Intent(implicit);
ComponentName cn=new ComponentName(svcInfo.applicationInfo.packageName,
svcInfo.name);

explicit.setComponent(cn);
appContext.bindService(explicit, this, Context.BIND_AUTO_CREATE);
}
else {
Toast.makeText(getActivity(), "Unexpected signature found!",
Toast.LENGTH_LONG).show();
}
}
catch (Exception e) {
Log.e(getClass().getSimpleName(), "Exception trying to get signature hash", e);
}
}

关于android - 如何使隐含的 Intent 明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35827703/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com