一、SharedPreferences將數據文件保存在指定路徑上
通過反射:
private void initSharedPreferences(String path,String name,int mode) { try { Field field =ContextWrapper.class.getDeclaredField("mBase"); field.setAccessible(true); Object obj = field.get(this); field = obj.getClass().getDeclaredField("mPreferencesDir"); field.setAccessible(true); File file = new File(path); field.set(obj, file); sharedPreferences = getSharedPreferences(name, mode); editor = sharedPreferences.edit(); } catch (Exception e) { e.printStackTrace(); } }
原理:
查看getSharedPreferences源碼(ContextImpl.java類)
@Override public SharedPreferences getSharedPreferences(String name, int mode) { SharedPreferencesImpl sp; synchronized (sSharedPrefs) { sp = sSharedPrefs.get(name); if (sp == null) { File prefsFile = getSharedPrefsFile(name); sp = new SharedPreferencesImpl(prefsFile, mode); sSharedPrefs.put(name, 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. sp.startReloadIfChangedUnexpectedly(); } return sp; }
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; } }