如何删除应用程序的SharedPreferences数据?

我正在创建一个使用大量web服务来同步数据的应用程序。出于测试目的,我需要在重新启动应用程序时删除一些SharedPreferences值。


当前回答

在类定义中:

private static final String PREFERENCES = "shared_prefs";

private static final SharedPreferences sharedPreferences  = getApplicationContext().getSharedPreferences(PREFERENCES, MODE_PRIVATE);

类内部:

public static void deleteAllSharedPrefs(){
    sharedPreferences.edit().clear().commit();
}

其他回答

如果不需要每次都删除它,您可以手动从:

>应用程序->管理应用程序->(选择您的应用程序) ->清除数据或卸载

更新版本的Android:

设置—>应用程序—>(选择应用程序)—>存储—>清理数据 和清空缓存

没有一个答案适合我,因为我有很多共享的首选项键。

假设你正在运行一个Android测试,而不是一个单元测试。

它为我工作循环和删除通过所有shared_prefs文件。

@BeforeClass将在所有测试和ActivityTestRule之前运行

@BeforeClass
public static void setUp() {
    Context context = InstrumentationRegistry.getTargetContext();

    File root = context.getFilesDir().getParentFile();
    String[] sharedPreferencesFileNames = new File(root, "shared_prefs").list();
    for (String fileName : sharedPreferencesFileNames) {
        context.getSharedPreferences(fileName.replace(".xml", ""), Context.MODE_PRIVATE).edit().clear().commit();
    }
}

要删除特定的值:SharedPreferences.Editor.remove()后面跟着一个commit()

SharedPreferences.Editor.clear()后面跟着一个commit()

如果您不关心返回值,并且从应用程序的主线程中使用它,请考虑使用apply()。

kotlin中的一行代码:

getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).edit().clear().apply()

对于Kotlin用户来说,这相当简单:

val sharedPref = context.getSharedPreferences("myPref", Context.MODE_PRIVATE)
 sharedPref.edit().clear().apply()