gpt4 book ai didi

java - 显式和隐式 Intent

转载 作者:行者123 更新时间:2023-11-29 19:10:53 25 4
gpt4 key购买 nike

我对Intents 有点困惑。

为什么是

Intent implicit=new Intent(IDownload.class.getName());  

隐式 Intent

同时

Intent explicit=new Intent(implicit);  

是一个明确的 Intent ,但它似乎没有在其定义中添加任何新内容。系统似乎没有提取任何先前未由上面的 implicit Intent 提供的新信息?

Android documentation (Intent types) ,

Explicit intents specify the component to start by name (the fully-qualified class name). You'll typically use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start......

Intent implicit=new Intent(IDownload.class.getName()); 似乎满足了这个要求,但仍被视为隐式 Intent ,根据文档:

Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it.....

Intent explicit=new Intent(implicit); 似乎与此矛盾,但仍被视为 Explicit intent。

更新 - 实现示例

引用:Binding to a Service

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setRetainInstance(true);

appContext=(Application)getActivity().getApplicationContext();

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

最佳答案

链接示例包括这些行

      Intent explicit=new Intent(implicit);
ComponentName cn=new ComponentName(svcInfo.applicationInfo.packageName,
svcInfo.name);

explicit.setComponent(cn);

第一行只是创建一个新的 Intent 实例,它是旧实例的副本。虽然变量可能是显式,但此时它仍然是隐式 Intent 。

第二行根据先前 getActivity().getPackageManager().queryIntentServices(implicit, 0) 调用的单个匹配结果创建一个 ComponentName 对象。在这一点上,explicit 仍然是隐式 Intent 。

第三行是魔法。一旦将特定的 ComponentName 分配给 Intent 实例,explicit 就真正成为了显式 Intent 。

关于java - 显式和隐式 Intent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45385187/

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