在Android中,有没有办法检查某个服务是否存在?

Wha*_*sUp 2 java service android exception

调用 时startActivity,可以尝试捕获 anActivityNotFoundException来了解活动是否存在。

然而打电话的时候startService却没有ServiceNotFoundException。如何检测该服务是否存在?

我为什么要这样做

据我所知,对的调用startService将被异步处理,因此我想知道我是否应该期望来自服务的响应(例如回调或广播)。

到目前为止我做了什么

我搜索了一下并在这里找到了一个相关问题。看来内部有一个ClassNotFoundException凸起。

是否可以在某处捕获此异常?这个Class.forName()方法似乎不对……是吗?

Com*_*are 5

如果是你自己的服务,你就知道你的服务是否存在。仅当您尝试使用某些第三方服务时,此问题才会出现。在这种情况下,请使用PackageManagerqueryIntentServices()来查看是否有与您的Intent.

例如,在此示例应用程序中,我使用queryIntentServices()

  • 确认我的只有一项匹配Intent

  • 将其从隐式转换Intent为显式Intent

  • 验证服务的签名密钥,以便我知道它不是伪装成我想要使用的服务(例如,使用恶意软件重新打包的应用程序)

大多数情况下,这是在onCreate()将绑定到服务的客户端片段中处理的:

  @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);
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)