在我的应用程序中,我查询在其 intent-filters 中具有特定类别的服务列表。这很好,我得到了一个包含 ResolveInfo 对象的列表。在这些 ResolveInfo 中,我找到了“serviceInfo”字段,它应该描述找到的服务的详细信息。
现在我如何从 serviceInfo 构造一个 Intent,它可以启动找到的服务?
我现在的代码是这样的:
PackageManager pm = getApplicationContext().getPackageManager();
Intent i = new Intent();
i.setAction("<my custom action>");
i.addCategory("<my custom category>");
List<ResolveInfo> l = pm.queryIntentServices(i, 0);
gatherAgentNum = l.size();
if(gatherAgentNum > 0){
for(ResolveInfo info : l){
Intent i2 = new Intent(this, info.serviceInfo.getClass());
i2.putExtra(BaseAgent.KEY_RESULT_RECEIVER, new GatherResult(mHandler));
startService(i2);
}
}
这显然是错误的,“info.serviceInfo.getClass()”只是返回 serviceInfo 对象的类。谁能帮我解决这个问题?
谢谢
编辑:解决方案(至少是我使用的那个):
PackageManager pm = getApplicationContext().getPackageManager();
Intent i = new Intent();
i.setAction("<my action>");
i.addCategory("<my category>");
List<ResolveInfo> l = pm.queryIntentServices(i, 0);
if(l.size() > 0){
for(ResolveInfo info : l){
ServiceInfo servInfo = info.serviceInfo;
ComponentName name = new ComponentName(servInfo.applicationInfo.packageName, servInfo.name);
Intent i2 = new Intent();
i2.setComponent(name);
startService(i2);
}
}
最佳答案
你看过吗:
- http://developer.android.com/reference/android/content/pm/ServiceInfo.html
- http://developer.android.com/reference/android/content/pm/PackageItemInfo.html#packageName
- http://developer.android.com/reference/android/content/pm/ApplicationInfo.html
我想您可以尝试用 .packageName
替换 getClass 类 - 并使用 packageManager.getLaunchIntentForPackage(String)
另请参阅:
- http://developer.android.com/reference/android/content/pm/PackageManager.html
queryIntentServices
,resolveService
关于android - 如何启动基于 ServiceInfo 对象的服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4291027/