How to programmatically check if a service is declared in AndroidManifest.xml?
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?
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;
}
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.
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.
精彩评论