2017-01-23 60 views
3

我有一個SharedPreference來計算我的應用程序的啓動量。我希望這是0,當我安裝我的應用程序。儘管如此,它仍然是14.我用我的數據庫觀察到的同樣奇怪的行爲已經存在於全新安裝中。SharedPreferences在重新安裝時不會重置

我並不打算回收我的應用程序數據(如在Google Cloud中)。在我的設備中,在帳戶設置中,應用數據同步處於打開狀態。如果我關掉它並重新安裝,我會觀察到同樣的行爲。

任何人都有觀察到這樣的行爲?有什麼辦法可以防止回收舊數據並強制進行正確安裝?

+6

難道這是因爲在Android的棉花糖推出了 「自動備份」 功能? [https://developer.android.com/guide/topics/data/autobackup.html](https://developer.android.com/guide/topics/data/autobackup.html) – Mauin

+0

就是這樣!大量的頭髮拉一行代碼... – Anthea

+1

@Mauin作出答覆,並得到信用 – Anthea

回答

4

在Android的棉花糖谷歌推出了其在默認情況下開啓,如果你的targetSdkVersion爲> = 23「自動備份」功能。

這將默認備份數據庫和SharedPreferences,並在重新安裝應用程序時進行恢復。要關閉此功能,您必須將android:allowBackup="false"添加到您的AndroidManifest.xml

此處瞭解詳情:Auto Backup for Apps

0

如果Android:allowBackup =「false」,則在標籤應用程序中查看AndroidManifest中的代碼。如果您沒有(默認情況下爲true),您的應用程序將參與android備份和恢復基礎架構,並且可以完全按照您的說法進行操作。

更多信息在這篇文章:What is "android:allowBackup"?

0

這需要從有關共享偏好設置應用程序方面處理。

創建一個共享首選項助手類,並在助手類中具有以下條件。

private static String SHARED_PREFS_VERSION = "SharedPrefsVersion"; // In this save the version of current shared Prefs. 

void SharedPrefsHelper() { 

    if(BuildConfig.Version > getSharedPrefsVersion()) { 

     SharedPreferences.Editor editor = prefs.edit(); editor.clear(); // Clear all the shared Prefs and update the current version. 

     SetSharedPrefsVersion(BuildConfig.Version); 

    } 
} 

更多參考一下:

https://stackoverflow.com/a/12381061/7364024