Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 349
lacker Avatar asked Jun 30 '11 01:06

lacker


2 Answers

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;
}
like image 99
Varun Avatar answered Nov 12 '22 01:11

Varun


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.

like image 42
lacker Avatar answered Nov 12 '22 02:11

lacker