如何基于ServiceInfo对象启动服务?

时间:2010-11-27 09:51:33

标签: android service

在我的应用中,我在其intent-filters中查询具有特定类别的服务列表。这很好,我得到一个包含ResolveInfo对象的List。在这些ResolveInfos中,我找到了“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);
            }
        }

1 个答案:

答案 0 :(得分:4)