Android main project with library project - how to

2019-02-25 19:04发布

问题:

Just started playing with Android and I'm trying to create an app that has free and paid version. I'm new to Java as well but I've managed to create a simple working application in Eclipse which consists of 2 main projects (one for the free version, and one for the paid version).

I also have a library project which contains shared code (activities, resources, strings etc) and is referenced by the main projects. What I want to do (and this may well be the wrong approach) is enable or disable things in the the library code depending on whether I'm running the free or paid version.

So for example I have a Main activity in the library project and I want to do something like:

if (version == "free") //version would somehow be set by the main project
{
   //disable a paid feature
}

Obviously I need to somehow work out in the library whether I'm running the free or paid main project so I can enable/disable features when I need to. What's the best approach to do this? For example could I use some kind of global setting in the main project, and somehow read this in the library project - I don't want the library project to know about the main project, if that makes sense?

I'm a quick study so feel free to point me in the direction of any articles, etc.

回答1:

Your code works, but I'm not sure storing your paid/free flag in your manifest is the best solution if you are using the same apk to have both free and paid (unlock) functionality. Instead I would do this by adding a method in the library project which allows any project to set a flag on whether the app is free or paid.

ex in library project:

    void setAppPurchasedMode(boolean purchased)
    {
        appPurchased = mode;
    }

and in your library, you can check vs this flag:

    if (appPurchased)
        // show unlocked content

So in your main project, if the app has been paid for:

    Library.setAppPurchasedMode(true);


回答2:

OK I managed to solve this. In the Application Manifest, I simply set the android:label property and referenced this using the code below.

In Manifest:

android:label="My Free App"

To reference this

//Are we using free or pro version?
if (this.getApplication().getApplicationInfo().loadLabel(this.getPackageManager()).toString().equals("My Free App")) 
{
freeVersion = true;
} else {
freeVersion = false;
}