Save SharedPreferences files into custom dir or get default SharedPreferences dir

六月ゝ 毕业季﹏ 提交于 2019-12-19 17:43:26

问题


Is it possible to save SharedPreferences files into custom dir? Let's say into /data/data/package.name/my_prefs/.

Or is it possible to retrieve the directory SharedPreferences are saved by default to?

P.S. Hardcoding the path /data/data/package.name/shared_prefs/ is not the solution.


回答1:


Or is it possible to retrieve the directory SharedPreferences are saved by default to?

Yes.

This is basically the dataDir /shared_prefs which you can get from the ApplicationInfo object (which in turn you can get from the PackageManager). (Also, it might be the same as the "getFilesDir" dir you can get easily from Context itself? Not sure, didn't check that.)

From the source, starting with Context.getSharedPreferences (ContextImpl source):

public SharedPreferences getSharedPreferences(String name, int mode) {
        SharedPreferencesImpl sp;
        File prefsFile;
        boolean needInitialLoad = false;
        synchronized (sSharedPrefs) {
            sp = sSharedPrefs.get(name);
            if (sp != null && !sp.hasFileChangedUnexpectedly()) {
                return sp;
            }
            prefsFile = getSharedPrefsFile(name);
...

public File getSharedPrefsFile(String name) {
        return makeFilename(getPreferencesDir(), name + ".xml");
    }

private File getPreferencesDir() {
        synchronized (mSync) {
            if (mPreferencesDir == null) {
                mPreferencesDir = new File(getDataDirFile(), "shared_prefs");
            }
            return mPreferencesDir;
        }
    }

private File getDataDirFile() {
        if (mPackageInfo != null) {
            return mPackageInfo.getDataDirFile();
        }
        throw new RuntimeException("Not supported in system context");
    }

And "mPackageInfo" is an instance of LoadedApk:

public File getDataDirFile() {
        return mDataDirFile;
    }

mDataDirFile = mDataDir != null ? new File(mDataDir) : null;

 mDataDir = aInfo.dataDir;

And that brings us back to ApplicationInfo.

I'd say if you don't want to rely on the convention /data/data/<package_name>/shared_prefs then it should be safe to get the "dataDir" and rely on "shared_prefs" from there?




回答2:


Or is it possible to retrieve the directory SharedPreferences are saved by default to?

See this answer to know how get path in safe way: https://stackoverflow.com/a/33849650/1504248



来源:https://stackoverflow.com/questions/8194883/save-sharedpreferences-files-into-custom-dir-or-get-default-sharedpreferences-di

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!