How to programmatically check if a service is declared in AndroidManifest.xml?

回眸只為那壹抹淺笑 提交于 2019-12-07 03:25:13

问题


I'm writing a library that provides a Service that is used by other developers by including it in their project. As such, I don't have control over the AndroidManifest.xml. I explain what to do in the docs, but nevertheless a common problem is that people neglect to add the appropriate <service/> tag to their manifest, or add it in the wrong place.

Right now, when my library calls startService while the service isn't declared in the manifest, the only thing that happens is that ActivityManager logs a warning. I would like to throw an exception when this happens so that developers know how to fix it. How can I detect whether the manifest actually declares this Service?


回答1:


I guess you should have a context in the library to do this. A cleaner way would be querying the packagemanager for the intent you want to start the service with.

public boolean isServiceAvailable(Context context, String action) {
    final PackageManager packageManager = context.getPackageManager();
    final Intent intent = new Intent(context, MyService.class);
    List resolveInfo =
            packageManager.queryIntentServices(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
   if (resolveInfo.size() > 0) {
     return true;
    }
   return false;
}



回答2:


Kind of silly for me to overlook this, but startService() returns null if there is no such service found, and returns the ComponentName otherwise. So that's the simplest way for me. It looks like using the PackageManager would also work.




回答3:


The PackageManager knows what services, activitys, and other stuff are installed. I haven't used it extensively but I believe getServiceInfo should satisfy your requirements.

You should be able to try and find the Service info for the component. If they forgot to put it in their manifest, an exception is thrown. You can catch this exception and throw your own informative one to the user.



来源:https://stackoverflow.com/questions/6529069/how-to-programmatically-check-if-a-service-is-declared-in-androidmanifest-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!