訪問SharedPreferences中的數據代碼如下:
SharedPreferences sharedPreferences = getSharedPreferences(“itcast”, Context.MODE_PRIVATE);
//getString()第二個參數為缺省值,如果preference中不存在該key,將返回缺省值
String name = sharedPreferences.getString(“name”, “”);
int age = sharedPreferences.getInt(“age”, 1);
如果訪問其他應用中的Preference,前提條件是:該preference創建時指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE權限。如:有個
getSharedPreferences(“itcast”, Context.MODE_WORLD_READABLE);
其他應用要訪問上面應用的preference,首先需要創建上面應用的Context,然后通過Context 訪問preference ,訪問preference時會在應用所在包下的shared_prefs目錄找到preference :
Context otherAppsContext = createPackageContext(“cn.itcast.action”, Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences(“itcast”, Context.MODE_WORLD_READABLE);
String name = sharedPreferences.getString(“name”, “”);
int age = sharedPreferences.getInt(“age”, 0);
如果不通過創建Context訪問其他應用的preference,可以以讀取xml文件方式直接訪問其他應用preference對應的xml文件,如:
File xmlFile = new File(“/data/data/