跨進程共享 SharedPreferences

String content = null;
		Context c = null;
		try {
			c = this.createPackageContext(PREFERENCE_PACKAGE,
					Context.CONTEXT_IGNORE_SECURITY);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.d(TAG, "" + c);
		SharedPreferences sh = c.getSharedPreferences(PREFERENCE_NAME, Context.MODE_WORLD_READABLE | Context.MODE_MULTI_PROCESS);
		content = sh.getString("tr069token3", null);

在android 4.0上通過以上方法可以跨進程訪問,之前沒有加入Context.MODE_MULTI_PROCESS參數,導致不能獲取到修改後的數據。在2.3的室內機上不能獲取,沒有權限。


下面是MODE_MULTI_PROCESS的說明:

SharedPreference loading flag: when set, the file on disk will be checked for modification even if the shared preferences instance is already loaded in this process. This behavior is sometimes desired in cases where the application has multiple processes, all writing to the same SharedPreferences file. Generally there are better forms of communication between processes, though.
This was the legacy (but undocumented) behavior in and before Gingerbread (Android 2.3) and this flag is implied when targetting such releases. For applications targetting SDK versions greater than Android 2.3, this flag must be explicitly set if desired.

也就是說,MODE_MULTI_PROCESS這個值是一個標誌,在Android 2.3及以前,這個標誌位都是默認開啓的,允許多個進程訪問同一個SharedPrecferences對象。而以後的Android版本,必須通過明確的將MODE_MULTI_PROCESS這個值傳遞給mode參數,才能開啓多進程訪問。



http://blog.chinaunix.net/uid-20771867-id-3085191.html

http://blog.csdn.net/elfylin/article/details/5988513 各個模式下生成的xml權限不一樣?

http://www.eoeandroid.com/thread-181297-1-1.html Context.MODE_PRIVATE存儲的數據是不能共享的?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章