I am trying to find something in Android and I am stuck when trying to apply a class in another .apk to my interface. I have an interface and various classes in other .apks that implement this interface. I find other classes using PackageManager query methods and use Application # createPackageContext () to get the class loader for this context. Then I load the class, create a new instance and try to pass it to my interface, which, as I know, definitely implements.
When I try to throw, it throws a class exception. I tried various things, such as loading the interface first, using classC # asSubclass, etc., None of which work. Class # getInterfaces () shows that the interface is implemented. My code is below:
PackageManager pm = getPackageManager();
List<ResolveInfo> lr = pm.queryIntentServices(new Intent("com.example.some.action"), 0);
ArrayList<MyInterface> list = new ArrayList<MyInterface>();
for (ResolveInfo r : lr) {
try {
Context c = getApplication().createPackageContext(r.serviceInfo.packageName, Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE);
ClassLoader cl = c.getClassLoader();
String className = r.serviceInfo.name;
if (className != null) {
try {
Class<?> cls = cl.loadClass(className);
Object o = cls.newInstance();
if (o instanceof MyInterface) {
list.add((MyInterface) o);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (NameNotFoundException e1) {
e1.printStackTrace();
}
}
source
share