Android library project - how to get context?

I’m happy to reorganize code from different versions of the same application (paid / free) into Android library projects so that actual applications can simply set up the library and reduce code duplication.

One thing I'm starting to getApplicationContext() what getApplicationContext() inside the library code means? Is the same ApplicationContext , how could one get from child applications? What happens when I access the SharedPreferences from the getApplicationContext() library project instead of the getApplicationContext() source application? Will the SharedPreferences file be the same or different?

What if I used activity to access SharedPreferences ? Does it matter that the activity is now a library activity, not an original application? Is SharedPreferences the same?

Thanks for the clarification.

+8
android
source share
2 answers

When the APK is packaged, all classes will belong to the main application.

call getApplicationContext (). getPackageName (), and it will return the application package name, not the library package.

I have the same setup for a free / paid application and no problem when I moved my classes to a library project.

However, you must check your xml files (manifest, widgets, etc.) to use the fully qualified package name of your library project.

+13
source share

A library project is like having all the code in one project. There are a few things to keep track of associated with namespaces, but overall it works very well.

eg. Your library has its own namespace

Library package name = uk.co.lib Main application package name = uk.co.app

The actions in the library in which you want to access from the main application must be added to the application manifest. An activity named A in the library project will be added to the manifest in the main application, for example:

 <activity android:name="uk.co.lib.A"> 

Access to general settings, etc. will give the same result from any namespace and return the settings for the application.

There is only one application, so there is only one ApplicationContext

+1
source share

All Articles