开发者

Abstract classes in Android library

开发者 https://www.devze.com 2023-01-09 12:54 出处:网络
I have an abstract Activity in an Android library (AbstractActivity) that is supposed to be used in other applications as the base Activity.

I have an abstract Activity in an Android library (AbstractActivity) that is supposed to be used in other applications as the base Activity.

Since this Activity isn't supposed to be used directly, it isn't declared in the library AndroidManifest.xml file (the real reason is because the Activity is declared as abstract) and so I can't declare it in the applications AndroidManifest.xml file.

The real problem is that when I create an application that uses the library, two .apk files get deployed to the device, Library.apk and Application.apk, and when the Application.apk is started it closes with the following message in LogCat:

ERROR/AndroidRuntime(4709): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{foo.bar/foo.bar.ApplicationActivity}: java.lang.ClassNotFoundException: foo.bar.ApplicationActivity in loader dalvik.system.PathClassLoader@44bec098

Can I reference an abstract Act开发者_StackOverflow社区ivity that is declared in a library and use it as the base for an Activity in a project that references this library?


Deploying separate APKs is probably not want you want. The APKs live in different sandboxes and cannot access each other.

If you want to reuse code, create an Android library project (in Eclipse, open properties of your library project, select Android and check "Is Library" under the library section.

Then, reference the library by clicking "Add" under the library section in the projects that use this library.

You end up with a single APK then.


The best (and correct) way to do this is to use the solution @Michael has suggested. However, for completeness, I thought I'd offer another solution that would work with the current setup of two apk files if for some reason you want to avoid making the one apk a library. Also note that this won't work if the activity that subclasses the AbstractActivity is loaded first, this will only work if the subclass is instantiated or called from another Activity in the same application.

In another Activity you can instantiate a PathClassLoader like so

PathClassLoader loader = new PathClassLoader("/data/data/com.yourlibrarypackage.apk", PathClassLoader.getSystemClassLoader());

And then use it to load the class you want

loader.loadClass("com.yourpackage.YourAbstractActivity")

The loadClass method returns a Class<T> object which you can ignore because it has the side-effect of making it available to other classes sharing the same memory space. That call is akin to Class.forName().

0

精彩评论

暂无评论...
验证码 换一张
取 消