标签:des android style blog io ar color os sp
一、SharedPreferences将数据文件保存在指定路径上
通过反射:
<span style="color:#333333;">private void initSharedPreferences(String path,String name,int mode) { try { </span><span style="color:#ff0000;">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);</span><span style="color:#333333;"> sharedPreferences = getSharedPreferences(name, mode); editor = sharedPreferences.edit(); } catch (Exception e) { e.printStackTrace(); } }</span>
原理:
查看getSharedPreferences源码(ContextImpl.java类)
<span style="color:#333333;"> @Override public SharedPreferences getSharedPreferences(String name, int mode) { SharedPreferencesImpl sp; synchronized (sSharedPrefs) { sp = sSharedPrefs.get(name); if (sp == null) { File prefsFile = </span><span style="color:#ff0000;">getSharedPrefsFile</span><span style="color:#333333;">(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; }</span>
public File getSharedPrefsFile(String name) { return makeFilename(<span style="color:#ff0000;">getPreferencesDir</span>(), name + ".xml"); }
private File getPreferencesDir() { synchronized (mSync) { if (<span style="color:#ff0000;">mPreferencesDir </span>== null) { mPreferencesDir = new File(<span style="color:#ff0000;">getDataDirFile</span>(), "shared_prefs"); } return mPreferencesDir; } }
标签:des android style blog io ar color os sp
原文地址:http://blog.csdn.net/w250shini11/article/details/41802997