訪問SharedPreferences中的數據代碼如下:
SharedPreferences sharedPreferences = getSharedPreferences("zyj", 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許可權。如:有個 name>為com.jbridge.pres.activity的應用使用下面語句創建了preference。 getSharedPreferences("zyj", Context.MODE_WORLD_READABLE);
其他應用要訪問上面應用的preference,首先需要創建上面應用的Context,然後通過Context 訪問preference ,訪問preference時會在應用所在包下的shared_prefs目錄找到preference :
Context otherAppsContext = createPackageContext("com.jbridge.pres.activity", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("zyj", 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/ /shared_prefs/zyj.xml”);// 應替換成應用的包名