简体   繁体   中英

How to share libgdx preference file between multiple android libgdx app

I have two android applications among which I want to share my preference files. What is the best way to go about this? I have tried setting a sharedUserId in the manifest of the two apps, however I am unsure on the additional settings required to achieve my requirements.

Any help in this regard would be much appreciated.

Thanks,

In your AndroidApplication subclass, you need to override getPreferences so it returns the preferences of your other installed app. I think the way to do this is to make one app the primary one that doesn't do anything special, and make the secondary app try to use the primary app's preferences, if the primary app is installed.

So override this only in the secondary app:

@Override
public Preferences getPreferences (String name) {
    try {
        Context primaryAppContext = 
            createPackageContext("com.package.of.primary.app", Context.MODE_PRIVATE);
            return new AndroidPreferences(primaryAppContext.getSharedPreferences(name, Context.MODE_PRIVATE));
    catch (PackageManager.NameNotFoundException e){} //other app not installed
    catch (SecurityException e){} //other app not accessible, maybe due to permissions
    return super.getPreferences(name); //fall back to local preferences
}

This will get more complicated if you need to handle the case where the second app is installed first and used for a while, and then the user installs the first app. Because now you might want the first app to become the secondary app instead, and the secondary app to become the primary app. Or you could check on installation of the primary app if the secondary app is already installed, and copy the secondary app's preferences over to the primary app.

There is also the case where the primary app is uninstalled but the user continues using the secondary app, at which point the preferences file is lost and the user suddenly is back to default settings.

Perhaps the safe thing to do is subclass Libgdx's AndroidPreferences and cause it to always write to SharedPreferences in both apps so they will always be in sync.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM