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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With