Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting customview from another application at runtime

I am struggling with the idea of getting CustomView from another application. Lets say I have two applications A and B. I know package name of CustomView, for example com.applicationb.CustomView. Is it possible to create an Object of this Class in application A at runtime?

My aim is to find a way to create CustomViews and being able to show them in my application. But I want them (views) to be a separate apk, which may be published to Android Market, and downloaded as some kind of extension.

CustomView would only display somekind of animation on screen (for example falling leaves). It would not work on any data in first application.

Edit

I found something like this:

@SuppressWarnings("rawtypes")
Class c = Class.forName(package_name);
Method m = c.getDeclaredMethod(method_name);
m.setAccessible(true);
Canvas can= (Canvas) m.invoke(null, null); // since there are no parameters, and called function is static

I hope this will work. I let you know.

like image 241
Jakub Szczygieł Avatar asked Aug 19 '26 21:08

Jakub Szczygieł


1 Answers

As I promissed here is result.

String packageName = "com.exapmle.sth";
String className = "com.exapmle.sth.CustomView";

String apkName = getPackageManager().getApplicationInfo(
    packageName, 0).sourceDir;
PathClassLoader myClassLoader = new dalvik.system.PathClassLoader(
    apkName, ClassLoader.getSystemClassLoader());
Class<?> handler = Class.forName(className, true, myClassLoader);
Constructor[] m = handler.getConstructors();
for (int i = 0; i < m.length; i++) {
    if (m[i].getName().contains("CustomView")) {
        animation = (View)m[i].newInstance(new Object[] { this });
        rootRL.addView(animation, new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.FILL_PARENT,
            RelativeLayout.LayoutParams.FILL_PARENT));
    }
}

With this code it is possible to get View from application B from using application A.

like image 57
Jakub Szczygieł Avatar answered Aug 21 '26 11:08

Jakub Szczygieł



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!