Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SharedPreferences解析 #46

Open
zengjingfang opened this issue Jul 21, 2018 · 0 comments
Open

SharedPreferences解析 #46

zengjingfang opened this issue Jul 21, 2018 · 0 comments

Comments

@zengjingfang
Copy link
Owner

zengjingfang commented Jul 21, 2018

初始化

SharedPreferencesImpl

  • mFile 实际SharedPreferences数据存储文件,文件后缀名为“.xml”
  • mBackupFile 备份文件,文件后缀名为“.bak”
  • mMap 内存缓存
    SharedPreferencesImpl(File file, int mode) {
        mFile = file;
        mBackupFile = makeBackupFile(file);
        mMode = mode;
        mLoaded = false;
        mMap = null;
        startLoadFromDisk();
    }
  • 如果存在备份文件,则把XML文件删掉,用备份文件来替换
  • 读取xml文件数据赋值给临时的map
  • 如果读到的数据不为null,则赋值给全局的mMap,也就是放到内存缓存中,并把mLoaded置为true
  • 如果map为null,还是给mMap new 一个对象,方便后面使用
    private void loadFromDisk() {
        synchronized (mLock) {
            if (mLoaded) {
                return;
            }
            // 如果存在备份文件,则把XML文件删掉,用备份文件来替换
            if (mBackupFile.exists()) {
                mFile.delete();
                mBackupFile.renameTo(mFile);
            }
        }

        // Debugging
        if (mFile.exists() && !mFile.canRead()) {
            Log.w(TAG, "Attempt to read preferences file " + mFile + " without permission");
        }

        Map map = null;
        StructStat stat = null;
        try {
            stat = Os.stat(mFile.getPath());
            if (mFile.canRead()) {
                BufferedInputStream str = null;
                try {
                    str = new BufferedInputStream(
                            new FileInputStream(mFile), 16*1024);
                    // 将文件里的数据读取赋值给到map内存缓存
                    map = XmlUtils.readMapXml(str);
                } catch (Exception e) {
                    Log.w(TAG, "Cannot read " + mFile.getAbsolutePath(), e);
                } finally {
                    IoUtils.closeQuietly(str);
                }
            }
        } catch (ErrnoException e) {
            /* ignore */
        }

        synchronized (mLock) {
            mLoaded = true;
            if (map != null) {
                mMap = map;
                mStatTimestamp = stat.st_mtim;
                mStatSize = stat.st_size;
            } else {
                mMap = new HashMap<>();
            }
            mLock.notifyAll();
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant