美文网首页
SharedPreferences

SharedPreferences

作者: 大盗海洲 | 来源:发表于2019-05-29 12:15 被阅读0次
sp 初始化.jpg

使用

创建

 SharedPreferences sp = getSharedPreferences("sp_config", MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("sp_string","SharedPreferences");
        edit.putInt("sp_int",100);
        edit.apply();

调用

   SharedPreferences sp = getSharedPreferences("sp_config", MODE_PRIVATE);
        Map<String, ?> map = sp.getAll();
        for (Map.Entry<String, ?> entry:map.entrySet()){
            Log.d("TAG","Key="+entry.getKey()+" Values="+entry.getValue());
        }

log

D/TAG: Key=sp_string Values=SharedPreferences
D/TAG: Key=sp_int Values=100

源码分析

/**
 * Proxying implementation of Context that simply delegates all of its calls to
 * another Context.  Can be subclassed to modify behavior without changing
 * the original Context.
 */
//context 的代理类,context 是个抽象类,具体实现为contextImpl
public class ContextWrapper extends Context {
 Context mBase;
    public ContextWrapper(Context base) {
        mBase = base;
    }
    
   @Override
    public SharedPreferences getSharedPreferences(String name, int mode) {
        return mBase.getSharedPreferences(name, mode);
    }
}
/**
 * Common implementation of Context API, which provides the base
 * context object for Activity and other application components.
 */
  //Context 具体的实现类,为Activity 和application 提供基础组件
class ContextImpl extends Context {
    @Override
    public SharedPreferences getSharedPreferences(File file, int mode) {
        checkMode(mode);
        if (getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.O) {
            if (isCredentialProtectedStorage()
                    && !getSystemService(StorageManager.class).isUserKeyUnlocked(
                            UserHandle.myUserId())
                    && !isBuggy()) {
                throw new IllegalStateException("SharedPreferences in credential encrypted "
                        + "storage are not available until after user is unlocked");
            }
        }
        SharedPreferencesImpl sp;
        synchronized (ContextImpl.class) {
            final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
            sp = cache.get(file);
            if (sp == null) {
                //创建sp
                sp = new SharedPreferencesImpl(file, mode);
                cache.put(file, sp);
                return sp;
            }
        }
        if ((mode & Context.MODE_MULTI_PROCESS) != 0 ||
            getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
            // If somebody else (some other process) changed the prefs
            // file behind our back, we reload it.  This has been the
            // historical (if undocumented) behavior.
            //如果其他人(其他一些进程)更改了我们后面的prefs文件,我们会重新加载它。 这是历史(无证)行为。
            sp.startReloadIfChangedUnexpectedly();
        }
        return sp;
    }
}

以应用包名为Key 缓存SharedPrefsCache,所以不要存放大的key和value在SharedPreferences中,否则会一直存储在内存中得不到释放,可能造成内存溢出,内存使用过高会频发引发GC( garbage collection),导致界面丢帧甚至ANR(Application Not Responding)。

class ContextImpl extends Context {
    /**
     * Map from package name, to preference name, to cached preferences.
     */
    @GuardedBy("ContextImpl.class")
    private static ArrayMap<String, ArrayMap<File, SharedPreferencesImpl>> sSharedPrefsCache;

      private ArrayMap<File, SharedPreferencesImpl> getSharedPreferencesCacheLocked() {
        if (sSharedPrefsCache == null) {
            sSharedPrefsCache = new ArrayMap<>();
        }

        final String packageName = getPackageName();
      //以应用包名为Key 缓存SharedPrefsCache
        ArrayMap<File, SharedPreferencesImpl> packagePrefs = sSharedPrefsCache.get(packageName);
        if (packagePrefs == null) {
            packagePrefs = new ArrayMap<>();
            sSharedPrefsCache.put(packageName, packagePrefs);
        }

        return packagePrefs;
    }
}

final class SharedPreferencesImpl implements SharedPreferences {
      SharedPreferencesImpl(File file, int mode) {
        mFile = file;
        mBackupFile = makeBackupFile(file);
        mMode = mode;
        mLoaded = false;
        mMap = null;
        startLoadFromDisk();
    }

   private void startLoadFromDisk() {
        synchronized (mLock) {
            mLoaded = false;
        }
        //开启线程,从磁盘加载文件
        new Thread("SharedPreferencesImpl-load") {
            public void run() {
                loadFromDisk();
            }
        }.start();
    }
}



    private void loadFromDisk() {
        synchronized (mLock) {
            if (mLoaded) {
                return;
            }
            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);
                   //从输入流里解析xml
                    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_mtime;
                mStatSize = stat.st_size;
            } else {
                mMap = new HashMap<>();
            }
            //唤醒所有线程在这个对象上的锁机制
            mLock.notifyAll();
        }
    }


sp.edit().putString("sp_string","SharedPreferences").apply();

final class SharedPreferencesImpl implements SharedPreferences {
  public void apply() {
            final long startTime = System.currentTimeMillis();
            //把数据提交到内存中,所有不用担心在使用apply异步操作出现读取脏数据
            final MemoryCommitResult mcr = commitToMemory();
            //创建一个异步线程,这里也是commit() 提交方式的区别,commit 是同步操作,而apply是异步操作
            final Runnable awaitCommit = new Runnable() {
                    public void run() {
                        try {
                            mcr.writtenToDiskLatch.await();
                        } catch (InterruptedException ignored) {
                        }

                        if (DEBUG && mcr.wasWritten) {
                            Log.d(TAG, mFile.getName() + ":" + mcr.memoryStateGeneration
                                    + " applied after " + (System.currentTimeMillis() - startTime)
                                    + " ms");
                        }
                    }
                };

            QueuedWork.addFinisher(awaitCommit);

            Runnable postWriteRunnable = new Runnable() {
                    public void run() {
                        awaitCommit.run();
                        QueuedWork.removeFinisher(awaitCommit);
                    }
                };
             //为写入操作开启了工作线程,不错造成UI线程阻塞
            SharedPreferencesImpl.this.enqueueDiskWrite(mcr, postWriteRunnable);

            // Okay to notify the listeners before it's hit disk
            // because the listeners should always get the same
            // SharedPreferences instance back, which has the
            // changes reflected in memory.
            notifyListeners(mcr);
        }
}

commit()

  public boolean commit() {
            long startTime = 0;

            if (DEBUG) {
                startTime = System.currentTimeMillis();
            }

            MemoryCommitResult mcr = commitToMemory();
            //postWriteRunnable 为null,为写入操作并没开启线程,所以是同步操作
            SharedPreferencesImpl.this.enqueueDiskWrite(
                mcr, null /* sync write on this thread okay */);
            try {
                mcr.writtenToDiskLatch.await();
            } catch (InterruptedException e) {
                return false;
            } finally {
                if (DEBUG) {
                    Log.d(TAG, mFile.getName() + ":" + mcr.memoryStateGeneration
                            + " committed after " + (System.currentTimeMillis() - startTime)
                            + " ms");
                }
            }
            notifyListeners(mcr);
            return mcr.writeToDiskResult;
        }

总结:

  • apply 是异步的, commit 是同步的;
    平时使用的时候,尽量使用 apply 避免卡主主线程。因为写入前都已经更新修改到缓存了,不用担心读到脏数据。
  • 初次读取数据会有概率的阻塞,是因为线程锁(SharePreferencesImpl.this)的原因,在初始化加载文件的时候,和读取数据的时候都会用到这个锁,而加载xml loadFromDisk 是 IO 耗时操作,虽然 loadFromDisk 操作被分配到另一个线程执行,但因为读取数据的时候,争用了这个锁,会发生概率卡顿。

参考地址:
从源码理解 SharedPreferences 的实现

相关文章

网友评论

      本文标题:SharedPreferences

      本文链接:https://www.haomeiwen.com/subject/bkhetctx.html